# standard
from pathlib import Path
from typing import Optional

# third party
import typer
from rich import box
from rich.table import Table

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


def _load_project(project_dir: Path) -> Project:
    meta_path = project_dir / "metadata.md"
    if meta_path.exists():
        meta, body = read_md(meta_path)
        return Project.from_dict(project_dir.name, meta, body)
    return Project(name=project_dir.name)


def list_projects(
    workspace: Optional[str] = typer.Option(
        None, "--workspace", "-w", help="Workspace name (default: from config)"
    ),
) -> None:
    """List all projects in a workspace."""
    ws = workspace or get_default_workspace()
    default = get_active_project(ws)
    project_names = get_all_projects(ws)

    projects = [_load_project(get_project_dir(ws, name)) for name in project_names]

    data = [
        {**proj.to_dict(), "workspace": ws, "default": proj.name == default}
        for proj in projects
    ]

    def human_output() -> None:  # pragma: no cover
        if not projects:
            console.print(f"[dim]No projects in workspace '{ws}'.[/dim]")
            return
        table = Table(box=box.SIMPLE, show_header=True, header_style="bold")
        table.add_column("Name")
        table.add_column("Default", width=10)
        for proj in projects:
            is_default = proj.name == default
            table.add_row(
                f"[bold]{proj.name}[/bold]" if is_default else proj.name,
                "[green]✓[/green]" if is_default else "",
            )
        console.print(table)

    append_log(ws, "projects", "list")
    success(data, human_fn=human_output)
