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

import logging
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

logger = logging.getLogger(__name__)

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


@router.post("/simple-test")
def simple_test():
    """Simple test endpoint with no dependencies."""
    logger.debug("Simple test endpoint called")
    return {"status": "ok", "message": "simple test works"}


def require_user(x_user_id: Optional[str] = Header(None)) -> 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: Optional[EmailStr] = None
    country: str = "US"
def resolve_user_email(user_id: str) -> str:
    """Fetch the signed-in user's email from Firestore or use user_id directly if it's an email."""
    # If user_id looks like an email, use it directly
    if "@" in user_id:
        return user_id
    # Otherwise, look up the user in Firestore
    user = storage.get_user(user_id)
    if not user or not user.get("email"):
        raise HTTPException(status_code=400, detail="No email found for the signed-in user.")
    return user["email"]



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


class CreateTokenRequest(BaseModel):
    name: str = Field(..., min_length=1, max_length=64)


@router.get("/ping")
def ping():
    """Simple health check - no auth required."""
    logger.debug("Ping request received")
    return {"pong": True}


@router.post("/test-token")
def test_token_creation(user_id: str = Depends(require_user)):
    """Test endpoint to debug token creation."""
    logger.debug("Test token endpoint called for user_id: %s", user_id)
    return {"success": True, "user_id": user_id, "message": "Test endpoint works"}


@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:
        email = resolve_user_email(user_id)
        status = connect_manager.get_account_status(account_id, email=email)
        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:
        email = resolve_user_email(user_id)
        account = connect_manager.create_developer_account(email=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:
        email = resolve_user_email(user_id)
        link = connect_manager.create_onboarding_link(
            account_id=req.account_id, refresh_url=req.refresh_url, return_url=req.return_url, email=email
        )
        return {"success": True, "onboarding_link": link}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/tokens")
def create_token(req: CreateTokenRequest, user_id: str = Depends(require_user)):
    """Create a new API token for the authenticated user."""
    logger.info("Creating API token for user_id: %s, name: %s", user_id, req.name)
    try:
        email = resolve_user_email(user_id)
        logger.debug("Resolved email: %s for user_id: %s", email, user_id)
        
        token_data = storage.create_api_token(email=email, name=req.name)
        logger.info("API token created successfully for email: %s", email)
        
        return {"success": True, "token": token_data}
    except HTTPException:
        raise
    except Exception as e:
        logger.exception("Failed to create token for user_id: %s", user_id)
        raise HTTPException(status_code=500, detail=f"Failed to create token: {str(e)}")


@router.get("/tokens")
def list_tokens(user_id: str = Depends(require_user)):
    """List all API tokens for the authenticated user."""
    logger.debug("Listing tokens for user_id: %s", user_id)
    try:
        email = resolve_user_email(user_id)
        tokens = storage.list_api_tokens(email=email)
        logger.debug("Found %d tokens for user_id: %s", len(tokens), user_id)
        return {"success": True, "tokens": tokens}
    except Exception as e:
        logger.exception("Failed to list tokens for user_id: %s", user_id)
        raise HTTPException(status_code=400, detail=str(e))


@router.delete("/tokens/{token_id}")
def revoke_token(token_id: str, user_id: str = Depends(require_user)):
    """Revoke an API token."""
    try:
        email = resolve_user_email(user_id)
        storage.revoke_api_token(email=email, token_id=token_id)
        return {"success": True, "message": "Token revoked"}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
