from __future__ import annotations

from pathlib import Path
from typing import Any

from one_run.constants import DEFAULT_RUNS_DIR
from one_run.status_store import read_metadata, read_status
from one_run.timefmt import iso_short


def _fmt(value: Any) -> str:
    return "-" if value is None else str(value)


def list_runs(*, state_filter: str | None = None, long: bool = False) -> int:
    project_root = Path.cwd().resolve()
    runs_root = project_root / DEFAULT_RUNS_DIR
    if not runs_root.exists():
        print("no runs found")
        return 0

    run_dirs = sorted([p for p in runs_root.iterdir() if p.is_dir()], reverse=True)
    if not run_dirs:
        print("no runs found")
        return 0

    if long:
        print("run_id\tstate\tbackend\ttimestamp\tstarted_at\tended_at\texit_code\tmessage")
    else:
        print("run_id\tstate\tbackend\ttimestamp")

    matched = 0
    for run_dir in run_dirs:
        metadata_path = run_dir / "metadata.json"
        status_path = run_dir / "status.json"
        if not metadata_path.exists() or not status_path.exists():
            continue
        metadata = read_metadata(metadata_path)
        status = read_status(status_path)
        if state_filter and status.state != state_filter:
            continue

        matched += 1
        if long:
            print(
                f"{run_dir.name}\t{status.state}\t{metadata.get('backend_type','?')}\t"
                f"{iso_short(metadata.get('timestamp'))}\t{iso_short(status.started_at)}\t"
                f"{iso_short(status.ended_at)}\t{_fmt(status.exit_code)}\t{_fmt(status.message)}"
            )
        else:
            print(
                f"{run_dir.name}\t{status.state}\t{metadata.get('backend_type','?')}\t"
                f"{iso_short(metadata.get('timestamp'))}"
            )

    if matched == 0:
        print("no runs matched filter")
    return 0
