from __future__ import annotations

import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch

from src.poc4.scenarios import ScenarioConfigError, load_demo_scenarios
from src.agent_console.profile import load_app_profile


class DemoScenarioConfigTest(unittest.TestCase):
    def test_profile_environment_overrides_json_defaults(self) -> None:
        path = Path(__file__).parents[1] / "config" / "app_profile.json"
        with patch.dict(
            "os.environ",
            {
                "AGENT_CONSOLE_SHORT_NAME": "SMILEGATE",
                "AGENT_CONSOLE_PAGE_TITLE": "SMILEGATE DATA & AI POC",
                "AGENT_CONSOLE_PRIMARY_COLOR": "#113F67",
            },
            clear=False,
        ):
            profile = load_app_profile(path)

        self.assertEqual(profile.short_name, "SMILEGATE")
        self.assertEqual(profile.page_title, "SMILEGATE DATA & AI POC")
        self.assertEqual(profile.primary_color, "#113F67")

    def test_profile_reads_dotenv_values(self) -> None:
        path = Path(__file__).parents[1] / "config" / "app_profile.json"
        with tempfile.TemporaryDirectory() as temp_dir:
            env_file = Path(temp_dir) / ".env"
            env_file.write_text("AGENT_CONSOLE_SHORT_NAME=SMILEGATE\n", encoding="utf-8")
            profile = load_app_profile(path, env_file)

        self.assertEqual(profile.short_name, "SMILEGATE")

    def test_smilegate_scenarios_are_enabled_and_unique(self) -> None:
        path = Path(__file__).parents[1] / "config" / "smilegate_demo_scenarios.json"
        scenarios = load_demo_scenarios(path)

        self.assertGreaterEqual(len(scenarios), 3)
        self.assertEqual(len(scenarios), len({item.scenario_id for item in scenarios}))
        self.assertTrue(all(item.question.strip() for item in scenarios))

    def test_duplicate_id_is_rejected(self) -> None:
        with tempfile.TemporaryDirectory() as temp_dir:
            path = Path(temp_dir) / "scenarios.json"
            path.write_text(
                json.dumps(
                    {
                        "scenarios": [
                            {"id": "HR-01", "title": "one", "question": "q1"},
                            {"id": "HR-01", "title": "two", "question": "q2"},
                        ]
                    }
                ),
                encoding="utf-8",
            )
            with self.assertRaises(ScenarioConfigError):
                load_demo_scenarios(path)


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