"""Tests for the dashboard API endpoints."""

import pytest
from unittest.mock import patch
from fastapi.testclient import TestClient

with patch.dict("os.environ", {
    "AI_PROXY_MASTER_KEY": "sk-test-e2e",
    "ANTHROPIC_API_KEY": "sk-ant-test",
    "REDIS_URL": "redis://localhost:6379/0",
}):
    from proxym.main import app

AUTH = {"Authorization": "Bearer sk-test-e2e"}


@pytest.fixture
def client(tmp_path):
    """Client with isolated account storage."""
    import proxym.dashboard._accounts as dash_accts
    import proxym.dashboard._costs as dash_costs
    import proxym.dashboard._system as dash_sys
    import proxym.dashboard._vms as dash_vms
    from proxym.accounts import AccountManager
    from proxym.virt import VMOrchestrator
    mgr = AccountManager(config_path=str(tmp_path / "accounts.json"))
    orch = VMOrchestrator(
        config_dir=str(tmp_path / "vms"),
        images_dir=str(tmp_path / "images"),
        overlays_dir=str(tmp_path / "overlays"),
    )
    dash_accts._acct_mgr = mgr
    dash_costs._acct_mgr = mgr
    dash_sys._acct_mgr = mgr
    dash_vms._vm_orch = orch
    dash_sys._vm_orch = orch
    return TestClient(app)


class TestAccountEndpoints:
    def test_list_empty(self, client):
        r = client.get("/dashboard/accounts", headers=AUTH)
        assert r.status_code == 200
        assert r.json()["accounts"] == []

    def test_create_account(self, client):
        r = client.post("/dashboard/accounts", json={
            "name": "Test Anthropic",
            "provider": "anthropic",
            "api_key": "sk-ant-test123",
            "email": "test@example.com",
            "daily_budget_usd": 5.0,
            "monthly_budget_usd": 60.0,
        }, headers=AUTH)
        assert r.status_code == 200
        data = r.json()
        assert data["name"] == "Test Anthropic"
        assert data["provider"] == "anthropic"
        assert data["active"] is True

    def test_create_and_list(self, client):
        client.post("/dashboard/accounts", json={
            "name": "Acct 1",
            "provider": "anthropic",
            "api_key": "sk-1",
        }, headers=AUTH)
        client.post("/dashboard/accounts", json={
            "name": "Acct 2",
            "provider": "openai",
            "api_key": "sk-2",
        }, headers=AUTH)
        r = client.get("/dashboard/accounts", headers=AUTH)
        assert len(r.json()["accounts"]) == 2

    def test_get_single_account(self, client):
        create_r = client.post("/dashboard/accounts", json={
            "name": "Test",
            "provider": "google",
            "api_key": "AI-test",
        }, headers=AUTH)
        acct_id = create_r.json()["id"]
        r = client.get(f"/dashboard/accounts/{acct_id}", headers=AUTH)
        assert r.status_code == 200
        assert r.json()["name"] == "Test"

    def test_get_nonexistent_account(self, client):
        r = client.get("/dashboard/accounts/fake-id", headers=AUTH)
        assert r.status_code == 404

    def test_delete_account(self, client):
        create_r = client.post("/dashboard/accounts", json={
            "name": "Deleteme",
            "provider": "deepseek",
            "api_key": "sk-ds",
        }, headers=AUTH)
        acct_id = create_r.json()["id"]
        r = client.delete(f"/dashboard/accounts/{acct_id}", headers=AUTH)
        assert r.status_code == 200
        r2 = client.get(f"/dashboard/accounts/{acct_id}", headers=AUTH)
        assert r2.status_code == 404

    def test_bind_tool_to_account(self, client):
        create_r = client.post("/dashboard/accounts", json={
            "name": "Tooltest",
            "provider": "anthropic",
            "api_key": "sk-tool",
        }, headers=AUTH)
        acct_id = create_r.json()["id"]
        r = client.post(f"/dashboard/accounts/{acct_id}/bind-tool", json={
            "tool_type": "roo_code",
            "tool_name": "Roo Code Main",
            "vm_id": "vm-123",
            "project_path": "/home/user/project",
        }, headers=AUTH)
        assert r.status_code == 200
        # Verify it's bound
        acct_r = client.get(f"/dashboard/accounts/{acct_id}", headers=AUTH)
        tools = acct_r.json()["tools"]
        assert len(tools) == 1
        assert tools[0]["type"] == "roo_code"


class TestCostEndpoints:
    def test_costs_empty(self, client):
        r = client.get("/dashboard/costs", headers=AUTH)
        assert r.status_code == 200
        data = r.json()
        assert data["accounts_count"] == 0

    def test_costs_with_accounts(self, client):
        client.post("/dashboard/accounts", json={
            "name": "A1",
            "provider": "anthropic",
            "api_key": "sk-1",
        }, headers=AUTH)
        r = client.get("/dashboard/costs", headers=AUTH)
        data = r.json()
        assert data["accounts_count"] == 1
        assert data["accounts_active"] == 1

    def test_detailed_costs(self, client):
        client.post("/dashboard/accounts", json={
            "name": "A1",
            "provider": "anthropic",
            "api_key": "sk-1",
            "daily_budget_usd": 5,
            "monthly_budget_usd": 60,
        }, headers=AUTH)
        r = client.get("/dashboard/costs/detailed", headers=AUTH)
        assert r.status_code == 200
        data = r.json()
        assert len(data["accounts"]) == 1
        assert "summary" in data


class TestVMEndpoints:
    def test_list_vms_empty(self, client):
        r = client.get("/dashboard/vms", headers=AUTH)
        assert r.status_code == 200
        assert r.json()["vms"] == []

    def test_create_vm(self, client):
        r = client.post("/dashboard/vms", json={
            "name": "test-vm",
            "account_id": "acct-123",
            "tool": "windsurf",
            "code_mount_host": "/home/user/projects",
        }, headers=AUTH)
        assert r.status_code == 200
        data = r.json()
        assert data["name"] == "test-vm"
        assert data["state"] == "stopped"

    def test_delete_vm(self, client):
        create_r = client.post("/dashboard/vms", json={
            "name": "deleteme",
            "tool": "cursor",
        }, headers=AUTH)
        vm_id = create_r.json()["id"]
        r = client.delete(f"/dashboard/vms/{vm_id}", headers=AUTH)
        assert r.status_code == 200


class TestSystemStatus:
    def test_system_status(self, client):
        r = client.get("/dashboard/system", headers=AUTH)
        assert r.status_code == 200
        data = r.json()
        assert "accounts" in data
        assert "vms" in data
        assert "libvirt" in data
