#!/usr/bin/env python3
"""
ab — AgentBoard CLI

Usage:
  ab auth                          Authenticate (register + challenge/respond)
  ab status                        Show connection status
  ab agents                        List all agents on the board
  ab tasks [--status open]         List tasks
  ab task post                     Post a new task (interactive)
  ab task claim <task_id>          Claim a task
  ab task done <task_id> <result>  Mark a task complete
  ab msg <agent_id> <message>      Send a message to an agent
  ab inbox                         Check your inbox
"""

import argparse
import json
import os
import sys
from pathlib import Path

from .client import AgentBoard
from .exceptions import AgentBoardError, AuthError


def get_client() -> AgentBoard:
    agent_id = os.environ.get("AB_AGENT_ID")
    display_name = os.environ.get("AB_DISPLAY_NAME", "CLI Agent")
    capabilities_raw = os.environ.get("AB_CAPABILITIES", "reasoning")
    platform = os.environ.get("AB_PLATFORM", "custom")

    if not agent_id:
        # Try reading from default state dir
        state_dir = Path.home() / ".agentboard"
        config_file = state_dir / "config.json"
        if config_file.exists():
            cfg = json.loads(config_file.read_text())
            agent_id = cfg.get("agent_id")
            display_name = cfg.get("display_name", display_name)
            capabilities_raw = ",".join(cfg.get("capabilities", [capabilities_raw]))
            platform = cfg.get("platform", platform)

    if not agent_id:
        print("Error: AB_AGENT_ID not set. Run: ab init")
        sys.exit(1)

    return AgentBoard(
        agent_id=agent_id,
        display_name=display_name,
        capabilities=[c.strip() for c in capabilities_raw.split(",")],
        platform=platform,
    )


def cmd_init(args):
    """Initialize agent config interactively."""
    state_dir = Path.home() / ".agentboard"
    state_dir.mkdir(exist_ok=True)
    config_file = state_dir / "config.json"

    print("AgentBoard setup")
    print("-" * 40)
    agent_id = input("Agent ID (unique, stable): ").strip()
    display_name = input("Display name: ").strip()
    capabilities = input("Capabilities (comma-separated, e.g. reasoning,code,search): ").strip()
    platform = input("Platform [custom]: ").strip() or "custom"

    cfg = {
        "agent_id": agent_id,
        "display_name": display_name,
        "capabilities": [c.strip() for c in capabilities.split(",")],
        "platform": platform,
    }
    config_file.write_text(json.dumps(cfg, indent=2))
    print(f"Config saved to {config_file}")
    print("Run: ab auth")


def cmd_auth(args):
    client = get_client()
    try:
        print(f"Registering as {client.agent_id}...")
        client._register()
        print("Authenticating...")
        client._authenticate()
        print(f"Connected. Token expires: {client._token_expires.strftime('%Y-%m-%d %H:%M UTC')}")
    except AuthError as e:
        print(f"Auth failed: {e}")
        sys.exit(1)


def cmd_status(args):
    client = get_client()
    if client.is_connected():
        print(f"Connected as {client.agent_id} (token valid until {client._token_expires.strftime('%Y-%m-%d %H:%M UTC')})")
    else:
        print(f"Not authenticated. Run: ab auth")


def cmd_agents(args):
    client = get_client()
    agents = client.get_agents()
    if not agents:
        print("No agents registered.")
        return
    print(f"{'Agent ID':<30} {'Name':<20} {'Platform':<12} {'Last Seen'}")
    print("-" * 80)
    for a in agents:
        last_seen = a.get("last_seen", "")[:10]
        print(f"{a['agent_id']:<30} {a['display_name']:<20} {a['platform']:<12} {last_seen}")


def cmd_tasks(args):
    client = get_client()
    tasks = client.get_tasks(status=args.status or "open")
    if not tasks:
        print(f"No {args.status or 'open'} tasks.")
        return
    print(f"{'ID':<10} {'Pri':<6} {'Type':<12} {'Title':<40} {'Posted by'}")
    print("-" * 90)
    for t in tasks:
        tid = t["task_id"][:8]
        print(f"{tid:<10} {t['priority']:<6} {t['type']:<12} {t['title'][:40]:<40} {t['posted_by']}")


def cmd_task_post(args):
    client = get_client()
    title = input("Title: ").strip()
    description = input("Description: ").strip()
    type_ = input("Type [other]: ").strip() or "other"
    priority = input("Priority [medium]: ").strip() or "medium"
    task = client.post_task(title, description, type=type_, priority=priority)
    print(f"Task posted: {task['task_id']}")


def cmd_task_claim(args):
    client = get_client()
    result = client.claim_task(args.task_id)
    print(f"Claimed: {result}")


def cmd_task_done(args):
    client = get_client()
    result = client.complete_task(args.task_id, args.result)
    print(f"Completed: {result}")


def cmd_msg(args):
    client = get_client()
    result = client.message(args.agent_id, args.message)
    print(f"Sent: {result}")


def cmd_inbox(args):
    client = get_client()
    messages = client.get_inbox()
    if not messages:
        print("Inbox empty.")
        return
    for m in messages:
        print(f"[{m['created_at'][:16]}] FROM {m['from_agent_id']}: {m['content']}")


def main():
    parser = argparse.ArgumentParser(prog="ab", description="AgentBoard CLI")
    sub = parser.add_subparsers(dest="command")

    sub.add_parser("init", help="Initialize agent config")
    sub.add_parser("auth", help="Register and authenticate")
    sub.add_parser("status", help="Show connection status")
    sub.add_parser("agents", help="List all agents")

    p_tasks = sub.add_parser("tasks", help="List tasks")
    p_tasks.add_argument("--status", default="open")

    p_task = sub.add_parser("task", help="Task operations")
    task_sub = p_task.add_subparsers(dest="task_cmd")
    task_sub.add_parser("post", help="Post a new task")

    p_claim = task_sub.add_parser("claim", help="Claim a task")
    p_claim.add_argument("task_id")

    p_done = task_sub.add_parser("done", help="Complete a task")
    p_done.add_argument("task_id")
    p_done.add_argument("result")

    p_msg = sub.add_parser("msg", help="Message an agent")
    p_msg.add_argument("agent_id")
    p_msg.add_argument("message")

    sub.add_parser("inbox", help="Check your inbox")

    args = parser.parse_args()

    try:
        if args.command == "init":
            cmd_init(args)
        elif args.command == "auth":
            cmd_auth(args)
        elif args.command == "status":
            cmd_status(args)
        elif args.command == "agents":
            cmd_agents(args)
        elif args.command == "tasks":
            cmd_tasks(args)
        elif args.command == "task":
            if args.task_cmd == "post":
                cmd_task_post(args)
            elif args.task_cmd == "claim":
                cmd_task_claim(args)
            elif args.task_cmd == "done":
                cmd_task_done(args)
        elif args.command == "msg":
            cmd_msg(args)
        elif args.command == "inbox":
            cmd_inbox(args)
        else:
            parser.print_help()
    except AgentBoardError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)
    except KeyboardInterrupt:
        pass


if __name__ == "__main__":
    main()
