"""API tests for workflow execution and provider health 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 WorkflowApiTest(unittest.TestCase):
    """Verify v1.4 workflow execution API contracts."""

    @classmethod
    def setUpClass(cls) -> None:
        """Initialize API app with isolated workspace config."""
        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 resources."""
        cls._tempdir.cleanup()

    def test_post_workflow_run_dry_run_returns_200(self) -> None:
        """Workflow run endpoint should return 200 for valid dry-run requests."""
        response = self.client.post(
            "/workflow/run",
            json={
                "usecase_id": "outreach_sdr",
                "inputs": {
                    "company": "Acme",
                    "domain": "acme.com",
                    "contacts": [{"email": "cto@acme.com", "title": "CTO", "industry": "software", "employee_count": 80}],
                },
                "dry_run": True,
                "auto_enroll": True,
            },
        )
        self.assertEqual(200, response.status_code)
        body = response.json()
        self.assertEqual("outreach_sdr", body["usecase_id"])
        self.assertTrue(body["dry_run"])

    def test_post_workflow_run_unknown_usecase_returns_422(self) -> None:
        """Unknown use case ID should produce validation-style 422 response."""
        response = self.client.post(
            "/workflow/run",
            json={"usecase_id": "unknown_usecase", "inputs": {}, "dry_run": True},
        )
        self.assertEqual(422, response.status_code)
        self.assertIn("error", response.json())

    def test_post_providers_health_returns_provider_list(self) -> None:
        """Provider health endpoint should include available provider names."""
        response = self.client.post("/providers/health", json={})
        self.assertEqual(200, response.status_code)
        body = response.json()
        self.assertIn("available", body)
        self.assertIn("mock", body["available"])
        self.assertIn("hubspot", body["available"])


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