import sys
from pathlib import Path

# Add backend directory to Python path
backend_dir = Path(__file__).resolve().parent.parent
if str(backend_dir) not in sys.path:
    sys.path.insert(0, str(backend_dir))

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import uvicorn
from app.database.database import engine, Base
from app.config import settings
from app.routers import auth, users, products, categories, cart, orders, wishlist, contact, models, brands
    
# Create uploads directory if it doesn't exist
uploads_dir = Path("uploads")
uploads_dir.mkdir(exist_ok=True)
    
# Create tables
Base.metadata.create_all(bind=engine)

# Create or update admin user
def create_admin_user():
    from app.database.database import SessionLocal
    from app.models.user import User
    from app.services.auth import get_password_hash
    
    db = SessionLocal()
    try:
        # First, delete any old admin users with different emails
        old_admins = db.query(User).filter(
            User.is_admin == True,
            User.email != settings.admin_email
        ).all()
        
        if old_admins:
            print(f"🗑️  Removing old admin users...")
            for old_admin in old_admins:
                print(f"   - Deleting old admin: {old_admin.email}")
                db.delete(old_admin)
            db.commit()
        
        # Check if admin with current email exists
        admin = db.query(User).filter(User.email == settings.admin_email).first()
        
        if admin:
            # Admin exists - update password if force reset is enabled
            if settings.force_admin_password_reset:
                admin.hashed_password = get_password_hash(settings.admin_password)
                admin.full_name = settings.admin_full_name
                admin.is_active = True
                admin.is_admin = True
                db.commit()
                print(f"🔄 Admin password RESET (force_admin_password_reset=True): {settings.admin_email}")
                print(f"📧 Email: {settings.admin_email}")
                print(f"🔐 New Password: {settings.admin_password}")
            else:
                print(f"ℹ️  Admin user exists: {settings.admin_email} (password unchanged)")
                print(f"💡 To reset password, set FORCE_ADMIN_PASSWORD_RESET=true and redeploy")
        else:
            # Create new admin user
            admin = User(
                email=settings.admin_email,
                full_name=settings.admin_full_name,
                hashed_password=get_password_hash(settings.admin_password),
                is_admin=True,
                is_active=True,
                must_change_password=False  # Let user decide when to change
            )
            db.add(admin)
            db.commit()
            print(f"✅ Admin user created: {settings.admin_email}")
            print(f"📧 Email: {settings.admin_email}")
            print(f"🔐 Password: {settings.admin_password}")
    except Exception as e:
        print(f"❌ Error creating admin user: {e}")
        import traceback
        traceback.print_exc()
        db.rollback()
    finally:
        db.close()

create_admin_user()

app = FastAPI(
    title="E-commerce API",
    description="Full-featured e-commerce API for clothing and shoes",
    version="1.0.0",
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=[settings.frontend_url, "http://localhost:3000", "http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(auth.router)
app.include_router(users.router)
app.include_router(products.router)
app.include_router(categories.router)
app.include_router(models.router)
app.include_router(brands.router)
app.include_router(cart.router)
app.include_router(orders.router)
app.include_router(wishlist.router)
app.include_router(contact.router)
app.include_router(contact.admin_router)  # Admin contact messages endpoints
app.include_router(contact.user_router)  # User messages endpoints

# Mount static files for uploads
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")


@app.get("/")
def read_root():
    return {
        "message": "E-commerce API",
        "version": "1.0.0",
        "docs": "/docs",
    }


@app.get("/health")
def health_check():
    return {"status": "healthy"}


if __name__ == "__main__":
    uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)