"""Vault file read/write endpoints for the control panel."""

from __future__ import annotations

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

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


class VaultFileResponse(BaseModel):
    path: str
    content: str
    metadata: dict


class VaultWriteRequest(BaseModel):
    content: str
    metadata: dict | None = None


class AgentSummary(BaseModel):
    name: str
    role: str
    status: str


# --- Identity files ---


@router.get("/identity")
async def get_identity_files(request: Request) -> dict[str, VaultFileResponse]:
    """Get all identity files (SOUL, USER, PROFILE, CONTRACT, MEMORY)."""
    vault = request.app.state.vault
    docs = vault.read_identity_files()
    return {
        name: VaultFileResponse(
            path=str(doc.path.relative_to(vault.vault_dir)),
            content=doc.content,
            metadata=doc.metadata,
        )
        for name, doc in docs.items()
    }


@router.get("/file/{file_path:path}")
async def get_vault_file(request: Request, file_path: str) -> VaultFileResponse:
    """Read a single vault file by relative path."""
    vault = request.app.state.vault
    try:
        doc = vault.read(file_path)
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=f"File not found: {file_path}") from exc
    return VaultFileResponse(
        path=file_path,
        content=doc.content,
        metadata=doc.metadata,
    )


@router.put("/file/{file_path:path}")
async def update_vault_file(
    request: Request, file_path: str, body: VaultWriteRequest
) -> VaultFileResponse:
    """Update a vault file. Creates it if it doesn't exist."""
    from agntspace.vault.writer import VaultWriter

    settings = request.app.state.settings
    writer = VaultWriter(settings.vault_dir)
    writer.write(file_path, body.content, body.metadata)

    # Read back to confirm
    vault = request.app.state.vault
    doc = vault.read(file_path)
    return VaultFileResponse(
        path=file_path,
        content=doc.content,
        metadata=doc.metadata,
    )


# --- Trust ---


@router.get("/trust")
async def get_trust(request: Request) -> VaultFileResponse:
    """Get trust.md scores."""
    vault = request.app.state.vault
    trust_path = vault.resolve_identity_path("trust.md")
    try:
        doc = vault.read(trust_path)
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail="trust.md not found") from exc
    return VaultFileResponse(
        path=trust_path,
        content=doc.content,
        metadata=doc.metadata,
    )


# --- Agents ---


@router.get("/agents")
async def list_agents(request: Request) -> list[AgentSummary]:
    """List all subagent definitions."""
    vault = request.app.state.vault
    files = vault.list_files("system/agents", "*.md")
    agents = []
    for f in files:
        try:
            doc = vault.read(f"system/agents/{f.name}")
            agents.append(
                AgentSummary(
                    name=doc.metadata.get("title", f.stem),
                    role=doc.metadata.get("role", ""),
                    status=doc.metadata.get("status", "active"),
                )
            )
        except Exception:
            continue
    return agents


@router.get("/agents/{agent_name}")
async def get_agent(request: Request, agent_name: str) -> VaultFileResponse:
    """Get a single subagent definition."""
    vault = request.app.state.vault
    path = f"system/agents/{agent_name}.md"
    try:
        doc = vault.read(path)
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=f"Agent not found: {agent_name}") from exc
    return VaultFileResponse(
        path=path,
        content=doc.content,
        metadata=doc.metadata,
    )


# --- Status ---


@router.get("/status")
async def vault_status(request: Request) -> dict:
    """Get vault overview: which files exist, counts."""
    vault = request.app.state.vault
    identity = vault.read_identity_files()
    agents = vault.list_files("system/agents", "*.md")
    journals = (
        vault.list_files("journal/user", "*.md")
        + vault.list_files("journal/agnt", "*.md")
        + vault.list_files("journal", "*.md")
    )
    tasks = vault.list_files("tasks", "*.md")
    goals = vault.list_files("goals", "*.md")

    return {
        "identity_files": list(identity.keys()),
        "agent_count": len(agents),
        "journal_count": len(journals),
        "task_count": len(tasks),
        "goal_count": len(goals),
        "onboarded": _is_onboarded(identity),
    }


def _is_onboarded(identity: dict) -> bool:
    """Check if the user has completed onboarding (PROFILE.md has real content)."""
    profile = identity.get("PROFILE")
    if not profile:
        return False
    # Default template has "[Your name]" placeholder
    return "[Your name]" not in profile.content and len(profile.content.strip()) > 200
