from fastapi import APIRouter, HTTPException

from app.config import settings
from app.services.diagnostics import DiagnosticsService
from app.services.paperless import PaperlessService
from app.services.repository import get_repository
from app.services.store import JsonStore


router = APIRouter(prefix="/api", tags=["paperless", "health"])
service = PaperlessService()
repo = get_repository()
store = JsonStore()
diagnostics = DiagnosticsService()


@router.get("/health")
async def health():
    return {"ok": True, "service": "doris-schoolhouse", "state_dir": settings.state_dir, "backend": repo.backend}


@router.get("/health/details")
async def health_details():
    return diagnostics.collect()


@router.post("/paperless/webhook/intake-enriched")
async def paperless_intake_enriched(submission_id: str, document_id: int, paperless_title: str | None = None):
    updated = repo.update_submission(
        submission_id,
        {
            "status": "paperless-linked",
            "paperless_document_id": document_id,
            "paperless_title": paperless_title,
            "paperless_linked_at": store.now(),
        },
    )
    if not updated:
        raise HTTPException(status_code=404, detail="Submission not found.")
    return {"status": "ok", "submission": updated}


@router.post("/paperless/webhook/recording-complete")
async def paperless_recording_complete(recording_id: str, transcript_document_id: int | None = None, summary_document_id: int | None = None, recording_document_id: int | None = None):
    updated = repo.update_recording(
        recording_id,
        {
            "status": "paperless-linked",
            "transcript_paperless_document_id": transcript_document_id,
            "summary_paperless_document_id": summary_document_id,
            "recording_paperless_document_id": recording_document_id,
            "transcription_status": "ready" if transcript_document_id else None,
            "summary_status": "ready" if summary_document_id else None,
            "paperless_linked_at": store.now(),
        },
    )
    if not updated:
        raise HTTPException(status_code=404, detail="Recording not found.")
    return {"status": "ok", "recording": updated}


@router.post("/paperless/assignments/{assignment_id}/append-grade-note")
async def append_grade_note(assignment_id: str, execute: bool = False):
    if not execute:
        return service.describe_grade_note_plan(assignment_id)
    try:
        return service.append_grade_note(assignment_id)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
