"""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_if_yaml, 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 print_json_if_yaml(args, 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_list(args, endpoint: str, item_name: str, columns: list, widths: list, empty_msg: str):
    """Generic list command wrapper."""
    from proxym.cli.utils.cmd_sessions_list import cmd_list_items as _cmd_list_items
    _cmd_list_items(args, endpoint, item_name, columns, widths, empty_msg)


def cmd_sessions_list(args):
    """List active agent sessions."""
    from proxym.cli.utils.cmd_sessions_list import cmd_sessions_list as _cmd_sessions_list
    _cmd_sessions_list(args)


def cmd_mcp_servers(args):
    """List registered MCP servers."""
    from proxym.cli.utils.cmd_sessions_list import cmd_mcp_servers as _cmd_mcp_servers
    _cmd_mcp_servers(args)
