"""
Inter-agent communication via tmux + shared files.

Usage from any agent:
    import sys; sys.path.insert(0, "/data/cameron/agents_stuff")
    from shared.comms import send_task, read_outbox, get_status, capture_pane, find_window

Usage from CLI:
    python -m shared.comms send backbones "Run OOD eval on viewpoint shifts"
    python -m shared.comms status backbones
    python -m shared.comms read backbones
    python -m shared.comms capture backbones
    python -m shared.comms broadcast "Check your ROLE.md for updated guidelines"
"""

import subprocess
import sys
import time
import yaml
from pathlib import Path
from datetime import datetime

REPO_ROOT = Path(__file__).resolve().parent.parent
AGENTS_DIR = REPO_ROOT / "agents"
CONFIG_PATH = REPO_ROOT / "config.yaml"


def _load_config():
    with open(CONFIG_PATH) as f:
        return yaml.safe_load(f)


def find_window(agent_name: str) -> str | None:
    """Find tmux session:window target by window name."""
    config = _load_config()
    if agent_name not in config["agents"]:
        return None
    session = config.get("session", "agents")
    result = subprocess.run(
        ["tmux", "list-windows", "-t", session, "-F", "#{session_name}:#{window_index} #{window_name}"],
        capture_output=True, text=True,
    )
    for line in result.stdout.strip().split("\n"):
        parts = line.split(" ", 1)
        if len(parts) == 2 and parts[1] == agent_name:
            return parts[0]
    return None


def send_task(agent_name: str, task: str, priority: str = "normal"):
    """Write a task to an agent's inbox and nudge them via tmux."""
    inbox = AGENTS_DIR / agent_name / "inbox.md"
    inbox.parent.mkdir(parents=True, exist_ok=True)
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    entry = f"\n---\n## Task ({priority}) — {timestamp}\n\n{task}\n"
    with open(inbox, "a") as f:
        f.write(entry)

    _write_status(agent_name, "task_pending")

    target = find_window(agent_name)
    if target:
        nudge = (
            f"You have a new task in {inbox} — read it and execute. "
            f"Write results to {AGENTS_DIR / agent_name / 'outbox.md'} "
            f"and update {AGENTS_DIR / agent_name / 'status.md'} to 'done' when finished."
        )
        subprocess.run(["tmux", "send-keys", "-t", target, nudge, "Enter"])
        time.sleep(1)
        subprocess.run(["tmux", "send-keys", "-t", target, "Enter"])
        return True
    print(f"Warning: tmux window for '{agent_name}' not found, task written to inbox only")
    return False


def read_outbox(agent_name: str) -> str:
    outbox = AGENTS_DIR / agent_name / "outbox.md"
    return outbox.read_text() if outbox.exists() else ""


def clear_outbox(agent_name: str):
    outbox = AGENTS_DIR / agent_name / "outbox.md"
    outbox.write_text("")


def get_status(agent_name: str) -> str:
    status_file = AGENTS_DIR / agent_name / "status.md"
    return status_file.read_text().strip() if status_file.exists() else "unknown"


def _write_status(agent_name: str, status: str):
    status_file = AGENTS_DIR / agent_name / "status.md"
    status_file.parent.mkdir(parents=True, exist_ok=True)
    status_file.write_text(status)


def capture_pane(agent_name: str, lines: int = 50) -> str:
    target = find_window(agent_name)
    if not target:
        return f"Window for '{agent_name}' not found"
    result = subprocess.run(
        ["tmux", "capture-pane", "-t", target, "-p", "-S", f"-{lines}"],
        capture_output=True, text=True,
    )
    return result.stdout


def broadcast(message: str):
    config = _load_config()
    for agent_name in config["agents"]:
        send_task(agent_name, message)


def update_guidelines(agent_name: str):
    """Nudge an agent to re-read their ROLE.md and project guidelines."""
    target = find_window(agent_name)
    if target:
        msg = (
            f"Re-read your role at {AGENTS_DIR / agent_name / 'ROLE.md'} "
            f"and the project guidelines at {REPO_ROOT / 'shared' / 'GUIDELINES.md'} — "
            f"follow any updated instructions."
        )
        subprocess.run(["tmux", "send-keys", "-t", target, msg, "Enter"])
        time.sleep(1)
        subprocess.run(["tmux", "send-keys", "-t", target, "Enter"])


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "help"

    if cmd == "send" and len(sys.argv) >= 4:
        send_task(sys.argv[2], " ".join(sys.argv[3:]))
    elif cmd == "status" and len(sys.argv) >= 3:
        print(get_status(sys.argv[2]))
    elif cmd == "read" and len(sys.argv) >= 3:
        print(read_outbox(sys.argv[2]))
    elif cmd == "capture" and len(sys.argv) >= 3:
        lines = int(sys.argv[3]) if len(sys.argv) > 3 else 50
        print(capture_pane(sys.argv[2], lines))
    elif cmd == "broadcast" and len(sys.argv) >= 3:
        broadcast(" ".join(sys.argv[2:]))
    elif cmd == "windows":
        config = _load_config()
        for name in config["agents"]:
            w = find_window(name)
            print(f"  {name}: {w or 'NOT FOUND'}")
    else:
        print("Usage:")
        print("  python -m shared.comms send <agent> <task>")
        print("  python -m shared.comms status <agent>")
        print("  python -m shared.comms read <agent>")
        print("  python -m shared.comms capture <agent> [lines]")
        print("  python -m shared.comms broadcast <message>")
        print("  python -m shared.comms windows")
