"""FastAPI tests for usecase/prompt/scaffold API endpoints."""

from __future__ import annotations

import importlib
import os
import tempfile
import unittest
from pathlib import Path

import yaml

from tests.test_helpers import base_config

try:  # pragma: no cover
    from fastapi.testclient import TestClient
except ImportError:  # pragma: no cover
    TestClient = None


@unittest.skipIf(TestClient is None, "fastapi not installed in this environment")
class PromptingApiTest(unittest.TestCase):
    """Validate prompt rendering and usecase listing endpoints."""

    @classmethod
    def setUpClass(cls) -> None:
        """Initialize API app against isolated test workspace."""
        cls._tempdir = tempfile.TemporaryDirectory()
        root = Path(cls._tempdir.name)
        workspace = root / "workspace"
        config_path = root / "config.yaml"

        config = base_config()
        config["workspace"]["root"] = str(workspace)
        config["llm"]["provider"] = "ollama"
        config["llm"]["api_key"] = ""
        config["email"]["smtp"]["host"] = "localhost"
        config["email"]["smtp"]["username"] = "test"
        config["email"]["smtp"]["password"] = "test"

        with config_path.open("w", encoding="utf-8") as handle:
            yaml.safe_dump(config, handle)

        os.environ["KIESSCLAW_CONFIG"] = str(config_path)
        import kiessclaw.api.app as api_app

        cls.api = importlib.reload(api_app)
        cls.client = TestClient(cls.api.app)

    @classmethod
    def tearDownClass(cls) -> None:
        """Dispose temporary workspace resources."""
        cls._tempdir.cleanup()

    def test_post_prompt_render_returns_schema(self) -> None:
        """POST /prompt/render should return prompt text and lint payload."""
        response = self.client.post(
            "/prompt/render",
            json={
                "usecase_id": "outreach_sdr",
                "template": "system",
                "inputs": {
                    "target_segment": "CTOs",
                    "offer": "audit",
                    "sender_name": "Alex",
                    "sender_email": "alex@example.com",
                    "cta": "Reply yes",
                },
                "deterministic": True,
            },
        )
        self.assertEqual(200, response.status_code)
        body = response.json()
        self.assertIn("prompt", body)
        self.assertIn("lint", body)
        self.assertEqual("outreach_sdr", body["usecase_id"])

    def test_get_usecases_returns_list(self) -> None:
        """GET /usecases should return six built-in specs."""
        response = self.client.get("/usecases")
        self.assertEqual(200, response.status_code)
        body = response.json()
        self.assertIsInstance(body, list)
        self.assertEqual(6, len(body))


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