"""CLI commands for MLD project management.

Provides: mld project list, mld project get
"""

from __future__ import annotations

import argparse
import json
import sys


def register_project_parser(subparsers: argparse._SubParsersAction) -> None:
    """Register the 'project' subcommand group."""
    proj_parser = subparsers.add_parser(
        "project",
        help="Manage projects",
        description="List and view projects.",
    )
    proj_sub = proj_parser.add_subparsers(dest="project_command")

    # -- project list --
    list_parser = proj_sub.add_parser("list", help="List projects")
    list_parser.add_argument("--search", help="Search by name")
    list_parser.add_argument("--status", help="Filter by status (active/archived/completed)")
    list_parser.add_argument("--json", action="store_true", dest="json_output", help="Output as JSON")

    # -- project get --
    get_parser = proj_sub.add_parser("get", help="Get project details")
    get_parser.add_argument("id", type=int, help="Project ID")
    get_parser.add_argument("--json", action="store_true", dest="json_output", help="Output as JSON")


def cmd_project(args: argparse.Namespace) -> None:
    """Dispatch project subcommands."""
    if args.project_command == "list":
        _cmd_list(args)
    elif args.project_command == "get":
        _cmd_get(args)
    else:
        print("Usage: mld project <list|get>", file=sys.stderr)
        sys.exit(1)


def _get_client():
    try:
        from mld_sdk.client import MLDClient

        return MLDClient()
    except ImportError:
        print(
            "Error: httpx is required. Install with: pip install mld-sdk[client]",
            file=sys.stderr,
        )
        sys.exit(1)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


def _cmd_list(args: argparse.Namespace) -> None:
    client = _get_client()
    projects = client.projects.list(
        search=args.search,
        status=args.status,
    )
    if args.json_output:
        print(json.dumps(projects, indent=2, default=str))
    else:
        if not projects:
            print("No projects found.")
        else:
            print(f"{'ID':<6} {'Name':<30} {'Status':<12} {'Experiments':<12}")
            print("-" * 62)
            for p in projects:
                print(
                    f"{p.get('id', ''):<6} "
                    f"{str(p.get('name', ''))[:28]:<30} "
                    f"{str(p.get('status', '')):<12} "
                    f"{p.get('experiment_count', 0):<12}"
                )
            print(f"\n{len(projects)} project(s)")
    client.close()


def _cmd_get(args: argparse.Namespace) -> None:
    client = _get_client()
    proj = client.projects.get(args.id)
    if args.json_output:
        print(json.dumps(proj, indent=2, default=str))
    else:
        print(f"Project #{proj.get('id')}")
        print(f"  Name:   {proj.get('name')}")
        print(f"  Status: {proj.get('status')}")
        if proj.get("description"):
            print(f"  Desc:   {proj.get('description')}")
        print(f"  Members: {proj.get('member_count', 0)}")
        print(f"  Experiments: {proj.get('experiment_count', 0)}")
        print(f"  Created: {proj.get('created_at')}")
    client.close()
