"""Daily cycle API: morning briefing + end-of-day report + focus + fill workflow."""

from __future__ import annotations

import asyncio

from fastapi import APIRouter, Request
from pydantic import BaseModel  # noqa: F401 — used by FocusRequest

router = APIRouter(prefix="/daily", tags=["daily"])


class FocusRequest(BaseModel):
    text: str


@router.get("/status")
async def daily_status(request: Request) -> dict:
    """Get daily cycle status."""
    return request.app.state.daily_cycle.status()


@router.post("/briefing")
async def generate_briefing(request: Request) -> dict:
    """Manually trigger morning briefing."""
    daily = request.app.state.daily_cycle
    briefing = await daily.generate_morning_briefing()
    return {"briefing": briefing}


@router.get("/briefing")
async def get_latest_briefing(request: Request) -> dict:
    """Get the latest morning briefing."""
    daily = request.app.state.daily_cycle
    return {"briefing": daily.latest_briefing or "No briefing generated yet. Trigger one with POST /api/daily/briefing."}


@router.post("/eod")
async def generate_eod(request: Request) -> dict:
    """Manually trigger end-of-day report."""
    daily = request.app.state.daily_cycle
    eod = await daily.generate_eod_report()
    return {"report": eod}


@router.get("/eod")
async def get_latest_eod(request: Request) -> dict:
    """Get the latest end-of-day report."""
    daily = request.app.state.daily_cycle
    return {"report": daily.latest_eod or "No end-of-day report yet. Trigger one with POST /api/daily/eod."}


@router.post("/run-workflow")
async def run_fill_workflow(request: Request) -> dict:
    """Manually trigger the journal fill workflow.

    Scans the last 7 days and generates all missing journal files
    (briefings, EOD reports, reflections, weekly). Retries indefinitely
    until every file is produced. Runs in background so the HTTP response
    returns immediately.
    """
    daily = request.app.state.daily_cycle

    if daily._fill_lock.locked():
        return {"status": "already_running", "message": "A fill workflow is already running. It will complete all missing files."}

    async def _run() -> None:
        try:
            await daily.run_fill_workflow()
        except Exception:
            import logging
            logging.getLogger(__name__).warning("Fill workflow background task failed", exc_info=True)

    asyncio.create_task(_run())
    return {"status": "started", "message": "Journal fill workflow started — generating all missing files in background."}


@router.post("/focus")
async def set_focus(request: Request, body: FocusRequest) -> dict:
    """Set today's focus in the journal's Focus section.

    This feeds into the morning briefing. The agent will honor your
    focus over auto-generated suggestions.
    """
    journal = request.app.state.journal
    journal.set_focus(body.text)
    from agntspace.infra.timezone import local_today
    today = local_today()
    return {"status": "ok", "date": today}


@router.get("/focus")
async def get_focus(request: Request) -> dict:
    """Get today's focus from the journal."""
    journal = request.app.state.journal
    from agntspace.infra.timezone import local_today
    today = local_today()
    content = journal.get_section("Focus")
    return {"date": today, "focus": content, "set": bool(content)}
