"""Developer Console routes: projects, usage, and connect status."""

from typing import Any, Dict, List, Optional

from fastapi import APIRouter, Depends, Header, HTTPException
from pydantic import BaseModel, Field, EmailStr

from agenticlypay.utils.firestore_storage import FirestoreStorage
from agenticlypay.connect import ConnectManager

router = APIRouter()
connect_manager = ConnectManager()
storage = FirestoreStorage()


def require_user(x_user_id: Optional[str] = Header(None, convert_underscores=False)) -> str:
    """Ensure every console request is associated with an authenticated user."""
    if not x_user_id:
        raise HTTPException(status_code=401, detail="User ID missing")
    return x_user_id


class CreateProjectRequest(BaseModel):
    name: str = Field(..., min_length=2, max_length=64)
    description: Optional[str] = None


@router.post("/projects")
def create_project(req: CreateProjectRequest, user_id: str = Depends(require_user)):
    """Create a new project."""
    project = storage.create_project(user_id=user_id, name=req.name)
    return {"success": True, "project": project}


@router.get("/projects")
def list_projects(user_id: str = Depends(require_user)):
    """List all projects for the current user."""
    projects = storage.get_projects(user_id=user_id)
    return {"success": True, "projects": projects}


class CreateAccountRequest(BaseModel):
    email: EmailStr
    country: str = "US"


class CreateOnboardingLinkRequest(BaseModel):
    account_id: str
    refresh_url: str
    return_url: str


@router.get("/usage")
def get_usage(email: str, last_days: int = 30, user_id: str = Depends(require_user)):
    """Get usage statistics for an email address."""
    usage = storage.get_usage_by_email(email, last_days=last_days)
    return {"success": True, "usage": usage}


@router.get("/account")
def get_account_status(account_id: Optional[str] = None, user_id: str = Depends(require_user)):
    """Get Stripe Connect account status."""
    if not account_id:
        return {"success": False, "message": "account_id required"}

    try:
        status = connect_manager.get_account_status(account_id)
        return {"success": True, "account": status}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/account/create")
def create_connect_account(req: CreateAccountRequest, user_id: str = Depends(require_user)):
    """Create a new Stripe Connect account."""
    try:
        account = connect_manager.create_developer_account(email=req.email, country=req.country)
        return {"success": True, "account": account}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/account/onboarding")
def create_onboarding_link(req: CreateOnboardingLinkRequest, user_id: str = Depends(require_user)):
    """Create an onboarding link for a Connect account."""
    try:
        link = connect_manager.create_onboarding_link(
            account_id=req.account_id, refresh_url=req.refresh_url, return_url=req.return_url
        )
        return {"success": True, "onboarding_link": link}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
