"""Tests for _tools_api.py REST endpoints via TestClient."""

import pytest
from unittest.mock import patch, MagicMock
from fastapi.testclient import TestClient
from fastapi import FastAPI

from proxym.tools import ToolRegistry, ToolCategory
from proxym.tools.executor import ToolExecutor, JobStatus


@pytest.fixture(autouse=True)
def reset_singletons():
    ToolRegistry._instance = None
    ToolExecutor._instance = None
    yield
    ToolRegistry._instance = None
    ToolExecutor._instance = None


@pytest.fixture
def client():
    app = FastAPI()
    from proxym.dashboard._tools_api import router
    app.include_router(router, prefix="/dashboard")
    return TestClient(app)


# ── List tools ────────────────────────────────────────────

class TestListTools:
    def test_returns_all_tools(self, client):
        r = client.get("/dashboard/tools/")
        assert r.status_code == 200
        data = r.json()
        assert "tools" in data
        assert data["count"] == 8  # builtins
        names = {t["name"] for t in data["tools"]}
        assert "aider" in names
        assert "claude-code" in names

    def test_filter_by_category(self, client):
        r = client.get("/dashboard/tools/?category=agent_cli")
        assert r.status_code == 200
        data = r.json()
        for t in data["tools"]:
            assert t["category"] == "agent_cli"

    def test_summary(self, client):
        r = client.get("/dashboard/tools/summary")
        assert r.status_code == 200
        data = r.json()
        assert data["total"] == 8
        assert "available" in data
        assert "tools" in data


# ── Get specific tool ─────────────────────────────────────

class TestGetTool:
    def test_get_aider(self, client):
        r = client.get("/dashboard/tools/aider")
        assert r.status_code == 200
        data = r.json()
        assert data["name"] == "aider"
        assert data["category"] == "agent_cli"

    def test_get_missing_tool(self, client):
        r = client.get("/dashboard/tools/nonexistent-xyz")
        assert r.status_code == 404


# ── Queue endpoints ───────────────────────────────────────

class TestQueueEndpoints:
    def test_queue_status_empty(self, client):
        r = client.get("/dashboard/tools/queue")
        assert r.status_code == 200
        data = r.json()
        assert data["total_jobs"] == 0
        assert data["running"] is False

    def test_list_jobs_empty(self, client):
        r = client.get("/dashboard/tools/queue/jobs")
        assert r.status_code == 200
        data = r.json()
        assert data["jobs"] == []
        assert data["count"] == 0

    def test_get_job_missing(self, client):
        r = client.get("/dashboard/tools/queue/jobs/nonexistent")
        assert r.status_code == 404

    def test_cancel_job_missing(self, client):
        r = client.post("/dashboard/tools/queue/jobs/nonexistent/cancel")
        assert r.status_code == 400


# ── Dispatch (requires ticket) ────────────────────────────

class TestDispatch:
    def test_dispatch_unknown_tool(self, client):
        r = client.post("/dashboard/tools/dispatch", json={
            "ticket_id": "TKT-FAKE",
            "tool": "nonexistent-xyz",
        })
        assert r.status_code == 404

    def test_dispatch_missing_ticket(self, client):
        r = client.post("/dashboard/tools/dispatch", json={
            "ticket_id": "TKT-DOESNOTEXIST",
            "tool": "aider",
        })
        # The ticket lookup should fail with 404
        assert r.status_code == 404



# ── Prompt preview (requires ticket) ─────────────────────

class TestPromptPreview:
    def test_preview_unknown_tool(self, client):
        r = client.post("/dashboard/tools/prompt/preview", json={
            "ticket_id": "TKT-1",
            "tool": "nonexistent-xyz",
        })
        assert r.status_code == 404
