"""Journal API endpoints.

User journal: one file per day with standardized sections.
  - Focus, Thoughts, Decisions, Learnings, Reflections
Agent observations: separate file (agent-observations_DATE.md).
"""

from __future__ import annotations

from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel

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


class JournalEntryResponse(BaseModel):
    date: str
    content: str
    metadata: dict


class JournalAppendRequest(BaseModel):
    text: str
    section: str = "Thoughts"


class JournalEntryListItem(BaseModel):
    date: str
    path: str


@router.get("/today")
async def get_today(request: Request) -> JournalEntryResponse:
    """Get or create today's user journal entry."""
    journal = request.app.state.journal
    doc = journal.get_today()
    # Return clean date (YYYY-MM-DD), not the filename stem which
    # includes the prefix (e.g. "user-journal_2026-04-12").
    from datetime import date as dt_date
    today = dt_date.today().isoformat()
    return JournalEntryResponse(
        date=today,
        content=doc.content,
        metadata=doc.metadata,
    )


@router.get("/entries")
async def list_entries(request: Request, limit: int = 30) -> list[JournalEntryListItem]:
    """List recent user journal entries."""
    journal = request.app.state.journal
    entries = journal.list_entries(limit=limit)
    return [JournalEntryListItem(**e) for e in entries]


@router.get("/entries/{date}")
async def get_entry(request: Request, date: str) -> JournalEntryResponse:
    """Get a specific user journal entry by date (YYYY-MM-DD)."""
    journal = request.app.state.journal
    doc = journal.get_entry(date)
    if not doc:
        raise HTTPException(status_code=404, detail=f"No journal entry for {date}")
    return JournalEntryResponse(
        date=date,
        content=doc.content,
        metadata=doc.metadata,
    )


@router.get("/section/{section}")
async def get_section(request: Request, section: str, date: str | None = None) -> dict:
    """Read a specific section from today's (or a specific date's) journal."""
    journal = request.app.state.journal
    valid = set(journal.get_user_section_keys())
    if section not in valid:
        raise HTTPException(status_code=400, detail=f"Invalid section: {section}. Use: {', '.join(sorted(valid))}")
    content = journal.get_section(section, date)
    return {"section": section, "content": content, "date": date or "today"}


@router.post("/append")
async def append_entry(request: Request, body: JournalAppendRequest) -> dict:
    """Append to a section of today's user journal.

    Valid sections: Focus, Thoughts, Decisions, Learnings, Reflections.
    """
    journal = request.app.state.journal
    section = body.section
    valid = set(journal.get_user_section_keys())
    if section not in valid:
        raise HTTPException(status_code=400, detail=f"Invalid section: {section}. Use: {', '.join(sorted(valid))}")

    journal.append_to_user(section, body.text)
    return {"status": "ok", "section": section, "author": "user"}


@router.get("/dates")
async def list_dates(request: Request, limit: int = 30) -> list[dict]:
    """List recent journal dates with available file types."""
    journal = request.app.state.journal
    return journal.list_dates(limit=limit)


@router.get("/file/{date}/{file_type}")
async def get_file(request: Request, date: str, file_type: str) -> JournalEntryResponse:
    """Get a specific journal file type for a date.

    file_type: journal, observations, briefing, eod
    """
    journal = request.app.state.journal
    valid_types = journal.get_valid_file_types()
    if file_type not in valid_types:
        raise HTTPException(status_code=400, detail=f"Invalid file_type: {file_type}. Use: {', '.join(sorted(valid_types))}")
    doc = journal.get_file_for_date(date, file_type)
    if not doc:
        raise HTTPException(status_code=404, detail=f"No {file_type} for {date}")
    return JournalEntryResponse(
        date=date,
        content=doc.content,
        metadata=doc.metadata,
    )


@router.get("/agent-observations")
async def get_agent_observations(request: Request, date: str | None = None) -> JournalEntryResponse:
    """Get agent observations for a date (defaults to today)."""
    journal = request.app.state.journal
    doc = journal.get_agent_observations(date)
    if not doc:
        raise HTTPException(status_code=404, detail=f"No agent observations for {date or 'today'}")
    return JournalEntryResponse(
        date=date or "today",
        content=doc.content,
        metadata=doc.metadata,
    )
