"""Maxlife88 Agent Application Portal - Main FastAPI server."""
import os
import logging
from pathlib import Path
from contextlib import asynccontextmanager
from dotenv import load_dotenv
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

ROOT_DIR = Path(__file__).parent
load_dotenv(ROOT_DIR / ".env")

# Import after dotenv load
from db import get_db, close_db  # noqa: E402
from routes_public import router as public_router  # noqa: E402
from routes_payment import router as payment_router  # noqa: E402
from routes_admin import router as admin_router  # noqa: E402
from auth import hash_password  # noqa: E402
from models import Settings  # noqa: E402

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)


async def seed_admin_and_settings():
    db = get_db()
    admin_email = os.environ.get("ADMIN_EMAIL", "admin@maxlife88.com").lower()
    admin_password = os.environ.get("ADMIN_PASSWORD", "Admin@Maxlife88")
    existing = await db.admins.find_one({"email": admin_email}, {"_id": 0})
    if not existing:
        await db.admins.insert_one({
            "email": admin_email,
            "password_hash": hash_password(admin_password),
            "role": "admin",
        })
        logger.info("Seeded default admin user: %s", admin_email)
    # Seed default settings if missing
    if not await db.settings.find_one({"id": "global"}):
        s = Settings()
        await db.settings.insert_one(s.model_dump())
        logger.info("Seeded default settings (fee=$%s)", s.agent_fee_usd)
    # One-time migration: if DB is missing NOWPayments/SMTP keys but env has them,
    # copy them to DB so they survive `.env` loss on cPanel migrations.
    settings_doc = await db.settings.find_one({"id": "global"}, {"_id": 0}) or {}
    env_migrations = {
        "nowpayments_api_key": os.environ.get("NOWPAYMENTS_API_KEY", "").strip(),
        "nowpayments_ipn_secret": os.environ.get("NOWPAYMENTS_IPN_SECRET", "").strip(),
        "nowpayments_public_url": os.environ.get("PUBLIC_URL", "").strip(),
        "smtp_host": os.environ.get("SMTP_HOST", "").strip(),
        "smtp_user": os.environ.get("SMTP_USER", "").strip(),
        "smtp_password": os.environ.get("SMTP_PASSWORD", "").strip(),
    }
    to_set = {k: v for k, v in env_migrations.items() if v and not settings_doc.get(k)}
    if to_set:
        await db.settings.update_one({"id": "global"}, {"$set": to_set})
        logger.info("Migrated %d env keys → DB settings: %s", len(to_set), list(to_set.keys()))
    # Index for faster admin queries
    try:
        await db.applications.create_index("id", unique=True)
        await db.applications.create_index("email")
        await db.applications.create_index("status")
        await db.coupons.create_index("code", unique=True)
        await db.coupons.create_index("id", unique=True)
    except Exception as e:
        logger.warning("Index creation: %s", e)


@asynccontextmanager
async def lifespan(app: FastAPI):
    await seed_admin_and_settings()
    yield
    await close_db()


app = FastAPI(
    title="Maxlife88 Agent Portal API",
    version="1.0.0",
    lifespan=lifespan,
)

# CORS
app.add_middleware(
    CORSMiddleware,
    allow_credentials=True,
    allow_origins=os.environ.get("CORS_ORIGINS", "*").split(","),
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(public_router)
app.include_router(payment_router)
app.include_router(admin_router)


@app.get("/api/")
async def root():
    return {"message": "Maxlife88 Agent Portal API", "version": "1.0.0"}


@app.get("/api/health")
async def health():
    return {"ok": True}
