# standard
from typing import Optional

# third party
import typer
from rich import box
from rich.panel import Panel

# custom
from sunwaee.config import get_active_project, get_default_workspace, get_project_dir
from sunwaee.core.audit import append_log
from sunwaee.core.fs import read_md
from sunwaee.core.logger import get_logger
from sunwaee.core.output import console, error, success
from sunwaee.modules.projects.model import Project

_log = get_logger("modules.projects")


def read(
    name: str = typer.Argument(..., help="Project name"),
    workspace: Optional[str] = typer.Option(
        None, "--workspace", "-w", help="Workspace name (default: from config)"
    ),
) -> None:
    """Read a project."""
    ws = workspace or get_default_workspace()
    project_dir = get_project_dir(ws, name)
    if not project_dir.exists():
        _log.warning("Project not found: %r in workspace %r", name, ws)
        error(f"Project not found: {name!r}", "NOT_FOUND")

    meta_path = project_dir / "metadata.md"
    if meta_path.exists():
        meta, body = read_md(meta_path)
        proj = Project.from_dict(name, meta, body)
    else:
        proj = Project(name=name)

    _log.debug("Reading project %r (id=%s)", proj.name, proj.id)
    append_log(ws, "projects", "read", item_id=proj.id, item_title=name)

    def human_output() -> None:  # pragma: no cover
        from rich.markdown import Markdown

        is_default = get_active_project(ws) == name
        meta_line = "\n".join([
            f"[dim]id:[/dim] {proj.id[:8]}  "
            f"[dim]workspace:[/dim] {ws}  "
            f"[dim]default:[/dim] {'yes' if is_default else 'no'}  "
            f"[dim]created:[/dim] {proj.created_at[:10]}  "
            f"[dim]updated:[/dim] {proj.updated_at[:10]}",
        ])
        console.print(
            Panel(
                meta_line,
                title=f"[bold]{proj.name}[/bold]",
                box=box.ROUNDED,
                expand=False,
            )
        )
        if proj.body:
            console.print(Markdown(proj.body))

    data = proj.to_dict()
    data["workspace"] = ws
    data["default"] = get_active_project(ws) == name
    success(data, human_fn=human_output)
