"""Notes routes."""

from pathlib import Path

from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from app.core.db import get_db
from app.schemas.export import ExportReportRead
from app.schemas.notes import NotesGenerateRequest
from app.services import notes_generator
from app.services.integrations import service as integrations_service

router = APIRouter(prefix="/notes", tags=["notes"])
PROJECT_ROOT = Path(__file__).resolve().parents[3]


@router.post("/generate", response_model=ExportReportRead)
def generate_notes(
    engagement_id: int | None = Query(default=None, ge=1),
    include_vault: bool = Query(default=False),
    vault_query: str | None = Query(default=None, max_length=600),
    payload: NotesGenerateRequest | None = Body(default=None),
    db: Session = Depends(get_db),
) -> ExportReportRead:
    """Generate (or append) engagement notes markdown."""
    selected_engagement_id = payload.engagement_id if payload and payload.engagement_id is not None else engagement_id
    selected_include_vault = payload.include_vault if payload is not None else include_vault
    selected_vault_query = payload.vault_query if payload is not None else vault_query
    selected_provider_targets = payload.notes_provider_targets if payload is not None else None

    if selected_engagement_id is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="engagement_id is required",
        )

    try:
        path = notes_generator.generate_notes(
            db=db,
            engagement_id=selected_engagement_id,
            include_vault=selected_include_vault,
            vault_query=selected_vault_query,
        )
    except LookupError as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
    except Exception as exc:  # pragma: no cover - defensive runtime branch
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc)) from exc

    if selected_provider_targets:
        file_path = (PROJECT_ROOT / path).resolve()
        title = f"Engagement {selected_engagement_id} Notes"
        try:
            content = file_path.read_text(encoding="utf-8")
            integrations_service.write_generated_notes(
                title=title,
                content=content,
                provider_ids=list(selected_provider_targets),
                db=db,
            )
            db.commit()
        except Exception as exc:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Notes generated locally but provider write failed: {exc}",
            ) from exc

    return ExportReportRead(status="generated", path=path)
