import subprocess
import time
import pytest
from onako.tmux_orchestrator import TmuxOrchestrator

SESSION_NAME = "onako-term-test"


@pytest.fixture(autouse=True)
def cleanup():
    subprocess.run(["tmux", "kill-session", "-t", SESSION_NAME], capture_output=True)
    yield
    subprocess.run(["tmux", "kill-session", "-t", SESSION_NAME], capture_output=True)


@pytest.fixture
def orch(tmp_path):
    return TmuxOrchestrator(session_name=SESSION_NAME, db_path=tmp_path / "test.db")


def test_scratch_terminal_created_on_init(orch):
    result = subprocess.run(
        ["tmux", "list-windows", "-t", f"{SESSION_NAME}:", "-F", "#{window_name}"],
        capture_output=True, text=True,
    )
    windows = result.stdout.strip().split("\n")
    assert "term-scratch" in windows


def test_ensure_scratch_terminal_recreates_if_missing(orch):
    subprocess.run(
        ["tmux", "kill-window", "-t", f"{SESSION_NAME}:term-scratch"],
        capture_output=True,
    )
    orch.ensure_scratch_terminal()
    result = subprocess.run(
        ["tmux", "list-windows", "-t", f"{SESSION_NAME}:", "-F", "#{window_name}"],
        capture_output=True, text=True,
    )
    windows = result.stdout.strip().split("\n")
    assert "term-scratch" in windows


def test_create_companion_terminal(orch):
    orch.create_companion_terminal("task-abc123", "/tmp")
    result = subprocess.run(
        ["tmux", "list-windows", "-t", f"{SESSION_NAME}:", "-F", "#{window_name}"],
        capture_output=True, text=True,
    )
    windows = result.stdout.strip().split("\n")
    assert "term-task-abc123" in windows


def test_kill_companion_terminal(orch):
    orch.create_companion_terminal("task-abc123", "/tmp")
    orch.kill_companion_terminal("task-abc123")
    result = subprocess.run(
        ["tmux", "list-windows", "-t", f"{SESSION_NAME}:", "-F", "#{window_name}"],
        capture_output=True, text=True,
    )
    windows = result.stdout.strip().split("\n")
    assert "term-task-abc123" not in windows


def test_kill_companion_terminal_noop_if_missing(orch):
    orch.kill_companion_terminal("task-nonexistent")


def test_list_terminals(orch):
    terminals = orch.list_terminals()
    names = [t["name"] for t in terminals]
    assert "term-scratch" in names


def test_list_terminals_includes_companions(orch):
    orch.create_companion_terminal("task-abc123", "/tmp")
    terminals = orch.list_terminals()
    names = [t["name"] for t in terminals]
    assert "term-scratch" in names
    assert "term-task-abc123" in names


def test_terminal_output(orch):
    subprocess.run(
        ["tmux", "send-keys", "-t", f"{SESSION_NAME}:term-scratch",
         "echo term-output-test", "Enter"],
        check=True,
    )
    time.sleep(1)
    output = orch.get_terminal_output("term-scratch")
    assert "term-output-test" in output


def test_terminal_input(orch):
    subprocess.run(
        ["tmux", "send-keys", "-t", f"{SESSION_NAME}:term-scratch",
         "cat", "Enter"],
        check=True,
    )
    time.sleep(0.5)
    orch.send_terminal_input("term-scratch", "hello-term")
    time.sleep(1)
    output = orch.get_terminal_output("term-scratch")
    assert "hello-term" in output


def test_rediscover_skips_terminals(orch):
    orch.rediscover_tasks()
    task_ids = list(orch.tasks.keys())
    assert not any(tid.startswith("term-") for tid in task_ids)


def test_kill_task_also_kills_companion(orch):
    task = orch.create_task("sleep 999", branch="feat", worktree_path="/tmp")
    task_id = task["id"]
    # create_task auto-creates companion for branch tasks, so no manual creation needed
    orch.kill_task(task_id)
    result = subprocess.run(
        ["tmux", "list-windows", "-t", f"{SESSION_NAME}:", "-F", "#{window_name}"],
        capture_output=True, text=True,
    )
    windows = result.stdout.strip().split("\n")
    assert f"term-{task_id}" not in windows


def test_create_task_with_branch_creates_companion(orch):
    """Creating a task with a branch should also create a companion terminal."""
    task = orch.create_task("sleep 999", working_dir="/tmp", branch="feat", worktree_path="/tmp")
    task_id = task["id"]
    result = subprocess.run(
        ["tmux", "list-windows", "-t", f"{SESSION_NAME}:", "-F", "#{window_name}"],
        capture_output=True, text=True,
    )
    windows = result.stdout.strip().split("\n")
    assert f"term-{task_id}" in windows


def test_create_task_without_branch_no_companion(orch):
    """Creating a task without a branch should not create a companion terminal."""
    task = orch.create_task("sleep 999")
    task_id = task["id"]
    result = subprocess.run(
        ["tmux", "list-windows", "-t", f"{SESSION_NAME}:", "-F", "#{window_name}"],
        capture_output=True, text=True,
    )
    windows = result.stdout.strip().split("\n")
    assert f"term-{task_id}" not in windows


def test_resume_task_with_branch_creates_companion(orch):
    """Resuming a branch task should create a companion terminal."""
    task = orch.create_task("echo hello", branch="feat", worktree_path="/tmp")
    task_id = task["id"]
    orch.tasks[task_id]["claude_session_id"] = "fake-session"
    orch._save_task(orch.tasks[task_id])
    orch.kill_task(task_id)
    # Companion should be gone after kill
    orch.resume_task(task_id)
    result = subprocess.run(
        ["tmux", "list-windows", "-t", f"{SESSION_NAME}:", "-F", "#{window_name}"],
        capture_output=True, text=True,
    )
    windows = result.stdout.strip().split("\n")
    assert f"term-{task_id}" in windows
