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


class TestAnalyzeMain(unittest.TestCase):
    def test_writes_report_and_returns_at_risk_count(self):
        repo = Path(tempfile.mkdtemp())
        (repo / "CritMatic.lua").write_text("local x = GetSpellInfo(1)\n", encoding="utf-8")
        reports_dir = repo / "bot" / "reports"
        reports_dir.mkdir(parents=True)

        with patch(
            "bot.analyze.diff_api_surface",
            return_value=({"GetSpellInfo"}, set()),
        ):
            count, report_path, removed = analyze.run(
                branch="wow",
                new_version="11.3.0",
                new_build=110300,
                previous_version="11.2.7",
                previous_build=110207,
                repo_root=repo,
                reports_dir=reports_dir,
                detected_at="2026-05-06T13:42:11Z",
            )

        self.assertEqual(count, 1)
        self.assertTrue(report_path.exists())
        self.assertEqual(removed, {"GetSpellInfo"})
        body = report_path.read_text(encoding="utf-8")
        self.assertIn("GetSpellInfo", body)
        self.assertIn("CritMatic.lua", body)


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