"""Integration Tests for FastAPI Endpoints using TestClient."""
from __future__ import annotations

import unittest
from fastapi.testclient import TestClient

from backend.app.config.settings import settings
from backend.app.main import app


class TestAPIIntegration(unittest.TestCase):
    def setUp(self) -> None:
        self.client = TestClient(app)
        # Login as admin to obtain JWT
        login_res = self.client.post(
            "/api/v1/auth/login",
            json={"username": settings.ADMIN_USERNAME, "password": settings.ADMIN_PASSWORD},
        )
        self.assertEqual(login_res.status_code, 200)
        self.token = login_res.json()["access_token"]
        self.auth_headers = {"Authorization": f"Bearer {self.token}"}

    def test_health_endpoint(self) -> None:
        """Verify health check endpoint returns 200 and valid status."""
        res = self.client.get("/api/v1/health")
        self.assertEqual(res.status_code, 200)
        data = res.json()
        self.assertIn("status", data)
        self.assertIn("kill_switch_active", data)
        self.assertIn("trading_mode", data)

    def test_market_endpoints(self) -> None:
        """Verify symbols, ticker, and klines endpoints."""
        sym_res = self.client.get("/api/v1/market/symbols")
        self.assertEqual(sym_res.status_code, 200)
        self.assertIn("BTCUSDT", sym_res.json())

        ticker_res = self.client.get("/api/v1/market/ticker?symbol=BTCUSDT")
        self.assertEqual(ticker_res.status_code, 200)
        self.assertEqual(ticker_res.json()["symbol"], "BTCUSDT")

        klines_res = self.client.get("/api/v1/market/klines?symbol=BTCUSDT&limit=50")
        self.assertEqual(klines_res.status_code, 200)
        self.assertEqual(len(klines_res.json()), 50)

    def test_signals_endpoint(self) -> None:
        """Verify AI signal evaluation endpoint."""
        res = self.client.get("/api/v1/signals/latest?symbol=BTCUSDT")
        self.assertEqual(res.status_code, 200)
        data = res.json()
        self.assertIn(data["action"], ["LONG", "SHORT", "NO_TRADE"])
        self.assertIn("expected_value", data)

    def test_risk_status_endpoint(self) -> None:
        """Verify risk parameters and circuit breaker inspection."""
        res = self.client.get("/api/v1/risk/status")
        self.assertEqual(res.status_code, 200)
        data = res.json()
        self.assertIn("limits", data)
        self.assertIn("circuit_breaker", data)

    def test_backtest_execution_endpoint(self) -> None:
        """Verify backtest endpoint returns summary metrics and equity curve."""
        payload = {"symbol": "BTCUSDT", "interval": "15m", "bars": 100, "initial_equity": 10000.0}
        res = self.client.post("/api/v1/backtest/run", json=payload)
        self.assertEqual(res.status_code, 200)
        data = res.json()
        self.assertIn("summary", data)
        self.assertIn("equity_curve", data)
        self.assertIn("trades", data)

    def test_kill_switch_trigger_and_reset(self) -> None:
        """Verify emergency kill switch can be triggered and reset via authenticated API."""
        # Trigger
        trig_res = self.client.post(
            "/api/v1/system/kill-switch/trigger",
            json={"reason": "Integration drill test"},
            headers=self.auth_headers,
        )
        self.assertEqual(trig_res.status_code, 200)

        # Check status
        ks_res = self.client.get("/api/v1/system/kill-switch")
        self.assertTrue(ks_res.json()["active"])

        # Reset
        reset_res = self.client.post(
            "/api/v1/system/kill-switch/reset",
            headers=self.auth_headers,
        )
        self.assertEqual(reset_res.status_code, 200)

        # Verify inactive
        ks_res_after = self.client.get("/api/v1/system/kill-switch")
        self.assertFalse(ks_res_after.json()["active"])


if __name__ == "__main__":
    unittest.main()
