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 admin user if doesn't exist
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:
        admin = db.query(User).filter(User.email == settings.admin_email).first()
        if not admin:
            try:
                hashed_password = get_password_hash(settings.admin_password)
            except Exception as hash_error:
                print(f"⚠️  Password hashing error: {hash_error}")
                print("⚠️  Using direct bcrypt hash as fallback...")
                # Fallback: use bcrypt directly to avoid passlib version issues
                import bcrypt
                hashed_password = bcrypt.hashpw(
                    settings.admin_password.encode('utf-8'),
                    bcrypt.gensalt()
                ).decode('utf-8')
            
            admin = User(
                email=settings.admin_email,
                full_name=settings.admin_full_name,
                hashed_password=hashed_password,
                is_admin=True,
                is_active=True,
                must_change_password=True  # Force password change on first login
            )
            db.add(admin)
            db.commit()
            print(f"✅ Admin user created: {settings.admin_email}")
            print(f"⚠️  Default password: {settings.admin_password} (CHANGE THIS!)")
        else:
            print(f"ℹ️  Admin user already exists: {settings.admin_email}")
    except Exception as e:
        print(f"❌ Error creating admin user: {e}")
        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

# 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)