"""
Regression Test Route
Chạy bộ test cases qua bất kỳ chatbot URL nào, trả kết quả cho con người đọc.
"""

import logging
from typing import Any

import httpx
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from pydantic import BaseModel

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/regression-test", tags=["Regression Test"])


class RunTestsRequest(BaseModel):
    target_url: str  # VD: http://172.16.2.207:5000/api/agent/chat-dev
    test_cases: list[dict[str, Any]]  # [{id, question, ...}]
    timeout: int = 60  # seconds


@router.post("/run", summary="Run all test cases against a target URL")
async def run_tests(req: RunTestsRequest):
    """
    Gửi từng test case tới target_url, trả về kết quả để con người review.
    """
    results = []

    async with httpx.AsyncClient(timeout=req.timeout) as client:
        for tc in req.test_cases:
            question = tc.get("question", "")
            tc_id = tc.get("id", "")

            try:
                resp = await client.post(
                    req.target_url,
                    json={"user_query": question},
                    headers={"Content-Type": "application/json"},
                )
                resp.raise_for_status()
                data = resp.json()

                results.append({
                    "id": tc_id,
                    "question": question,
                    "status": "success",
                    "response": data.get("ai_response", ""),
                    "trace_id": data.get("trace_id", ""),
                    "latency_ms": resp.elapsed.total_seconds() * 1000 if hasattr(resp, 'elapsed') else None,
                })
            except httpx.HTTPStatusError as e:
                results.append({
                    "id": tc_id, "question": question,
                    "status": "error",
                    "response": f"HTTP {e.response.status_code}",
                    "trace_id": "", "latency_ms": None,
                })
            except Exception as e:
                results.append({
                    "id": tc_id, "question": question,
                    "status": "error",
                    "response": str(e),
                    "trace_id": "", "latency_ms": None,
                })

    return {
        "status": "success",
        "total": len(results),
        "passed": sum(1 for r in results if r["status"] == "success"),
        "failed": sum(1 for r in results if r["status"] == "error"),
        "results": results,
    }
