"""Command-line interface.

This CLI is deliberately small. It exists as a smoke-test harness and a
convenience for quick manual checks.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from dataclasses import asdict

from zenhub_client import ZenhubClient
from zenhub_client.exceptions import ZenhubError


def _default_token() -> str:
    return os.getenv("ZENHUB_TOKEN") or os.getenv("ZENHUB_API_TOKEN") or ""


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="zenhub-cli")
    parser.add_argument(
        "--token",
        default=_default_token(),
        help="Zenhub API token (or set ZENHUB_TOKEN).",
    )
    parser.add_argument(
        "--endpoint",
        default=None,
        help="Override GraphQL endpoint (rarely needed).",
    )
    parser.add_argument("--timeout", type=int, default=30, help="HTTP timeout (seconds).")

    sub = parser.add_subparsers(dest="cmd", required=True)

    issue = sub.add_parser("issue", help="Fetch a single issue by repositoryGhId + issueNumber")
    issue.add_argument("--repository-gh-id", type=int, required=True)
    issue.add_argument("--issue-number", type=int, required=True)

    pipelines = sub.add_parser("pipelines", help="List pipelines for a workspace")
    pipelines.add_argument("--workspace-id", required=True)
    pipelines.add_argument("--first", type=int, default=50)

    sprint_current = sub.add_parser("sprint-current", help="Get current OPEN sprint")
    sprint_current.add_argument("--workspace-id", required=True)

    sprint_summary = sub.add_parser("sprint-summary", help="Summarise sprint workload points")
    sprint_summary.add_argument("--sprint-id", required=True)

    return parser


def main(argv: list[str] | None = None) -> int:
    args = _build_parser().parse_args(argv)

    if not args.token:
        print("Missing Zenhub token. Provide --token or set ZENHUB_TOKEN.", file=sys.stderr)
        return 2

    client = ZenhubClient(api_token=args.token, endpoint=args.endpoint, timeout_s=args.timeout)
    try:
        if args.cmd == "issue":
            issue = client.issues.get_issue_by_info(
                repository_gh_id=args.repository_gh_id,
                issue_number=args.issue_number,
            )
            print(json.dumps(asdict(issue), indent=2))

        elif args.cmd == "pipelines":
            items = client.pipelines.list_pipelines(args.workspace_id, first=args.first)
            print(json.dumps([asdict(p) for p in items], indent=2))

        elif args.cmd == "sprint-current":
            sprint = client.sprints.get_current_open_sprint(args.workspace_id)
            print(json.dumps(asdict(sprint), indent=2))

        elif args.cmd == "sprint-summary":
            summary = client.sprints.get_sprint_workload_points(args.sprint_id)
            out = asdict(summary)
            out["sprint"] = asdict(summary.sprint)
            print(json.dumps(out, indent=2))

        else:
            raise AssertionError(f"Unhandled command: {args.cmd}")

    except ZenhubError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1
    finally:
        client.close()

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
