"""CLI commands: context delta/detect/stats, sessions list, mcp servers."""

from __future__ import annotations

import json

from proxym.cli._client import make_client, print_json, print_table


def cmd_context_delta(args):
    """Push a context delta to the proxy."""
    payload = {
        "project_id": getattr(args, "project_id", "") or "",
        "diff_text": getattr(args, "diff_text", "") or "",
    }
    if getattr(args, "version", None) is not None:
        payload["version"] = args.version
    if getattr(args, "token_estimate", None) is not None:
        payload["token_estimate"] = args.token_estimate

    # Allow reading diff from file
    diff_file = getattr(args, "file", None)
    if diff_file:
        with open(diff_file) as f:
            payload["diff_text"] = f.read()

    with make_client() as c:
        r = c.post("/v1/context/delta", json=payload)
        data = r.json()

    if data.get("ok"):
        print(f"  ✓ Delta accepted (version={data.get('version')})")
    else:
        print(f"  ✗ Delta rejected: {data}")


def cmd_context_detect(args):
    """Detect project context from messages or paths."""
    payload = {}
    if getattr(args, "system_prompt", None):
        payload["system_prompt"] = args.system_prompt
    if getattr(args, "paths", None):
        payload["paths"] = [p.strip() for p in args.paths.split(",") if p.strip()]
    if getattr(args, "message", None):
        payload["messages"] = [{"role": "user", "content": args.message}]

    with make_client() as c:
        r = c.post("/v1/context/detect", json=payload)
        data = r.json()

    print(f"  Project:  {data.get('project_name', '?')} ({data.get('project_id', '?')})")
    print(f"  Root:     {data.get('project_root', '?')}")
    print(f"  Stack:    {data.get('stack', '?')}")
    if data.get("git_remote"):
        print(f"  Remote:   {data['git_remote']}")


def cmd_context_stats(args):
    """Show context store statistics."""
    with make_client() as c:
        r = c.get("/v1/context/stats")
        data = r.json()

    if getattr(args, "format", "table") == "yaml":
        print_json(data)
        return

    print("\n  Context Statistics\n")
    print(f"  Projects tracked: {data.get('projects_tracked', 0)}")
    print(f"  Files tracked:    {data.get('files_tracked', 0)}")
    print(f"  Tokens total:     {data.get('tokens_total', 0)}")
    print()


def cmd_sessions_list(args):
    """List active agent sessions."""
    with make_client() as c:
        r = c.get("/v1/sessions")
        data = r.json()

    sessions = data.get("sessions", [])
    if getattr(args, "format", "table") == "yaml":
        print_json(data)
        return

    print(f"\n  Sessions ({len(sessions)})\n")
    if not sessions:
        print("  No active sessions.\n")
        return

    print_table(
        sessions,
        ["id", "project_id", "age_seconds", "idle_seconds", "history_length"],
        [20, 25, 12, 12, 14],
    )
    print()


def cmd_mcp_servers(args):
    """List registered MCP servers."""
    with make_client() as c:
        r = c.get("/v1/mcp/servers")
        data = r.json()

    servers = data.get("servers", [])
    if getattr(args, "format", "table") == "yaml":
        print_json(data)
        return

    print(f"\n  MCP Servers ({len(servers)})\n")
    if not servers:
        print("  No MCP servers registered.\n")
        return

    print_table(
        servers,
        ["name", "url", "transport", "enabled", "priority"],
        [20, 40, 10, 8, 8],
    )
    print()
