"""
POST /cvs/me — authenticated CV creation/update endpoint (Phase 1.5).

Pipeline:
1. Validate JWT, extract user_id.
2. Fetch profile from public.profiles (firstname, lastname, phone, profession, city).
3. Fetch email from auth.users via admin API (always fresh, see decision D3).
4. Build PersonalInfo backend-side.
5. UPSERT CV row in public.cvs (UNIQUE on user_id).
6. Generate PDF via WeasyPrint (CPU-bound, run in thread).
7. Upload PDF to Storage best-effort (failure = pdf_url null + warning).
8. Generate signed URL (1h TTL) if upload succeeded.
9. Return {cvId, pdfUrl, warning?} as camelCase JSON.
"""

import logging

from fastapi import APIRouter, Depends, HTTPException, status

from app.core.security import get_current_user, CurrentUser
from app.schemas.cv import CVPayloadInput, CVResponse
from app.services import cv_service
from app.services.cv_service import fetch_cv_by_user, build_cv_response

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/cvs", tags=["cvs"])


# ----------------------------------------------------------------------------
# Endpoint
# ----------------------------------------------------------------------------

@router.post(
    "/me",
    response_model=CVResponse,
    status_code=status.HTTP_200_OK,
    summary="Create or update the authenticated user's CV and generate PDF",
)
async def upsert_my_cv(
    payload: CVPayloadInput,
    current_user: CurrentUser = Depends(get_current_user),
) -> CVResponse:
    user_id = current_user.user_id
    logger.info("POST /cvs/me — user=%s", user_id)
    return await cv_service.save_cv_for_user(user_id, payload)


@router.get(
    "/me",
    response_model=CVResponse,
    status_code=status.HTTP_200_OK,
    summary="Fetch the authenticated user's current CV (no regeneration)",
)
async def get_my_cv(
    current_user: CurrentUser = Depends(get_current_user),
) -> CVResponse:
    """
    Read the persisted CV for the current user. Generates a fresh signed URL
    for the stored PDF (the previous one expires after SIGNED_URL_TTL_SECONDS).

    Returns 404 if the user has not generated a CV yet — the frontend uses
    this to render the empty state with a "Create your first CV" CTA.
    """
    user_id = current_user.user_id
    logger.info("GET /cvs/me — user=%s", user_id)

    response = build_cv_response(user_id)
    if response is None:
        logger.info("No CV found for user=%s (empty state)", user_id)
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Aucun CV trouvé. Créez votre CV d'abord.",
        )

    logger.info("GET /cvs/me success (user=%s, cv_id=%s)", user_id, response.cv_id)
    return response
