#!/usr/bin/env python3
from __future__ import annotations

import subprocess
import sys
import tempfile
import unittest
from pathlib import Path


SCRIPT = Path(__file__).with_name("update_change_log.py").resolve()


def run(args: list[str], cwd: Path) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        args,
        cwd=cwd,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        timeout=60,
    )


class AgentChangeLogScriptTest(unittest.TestCase):
    def setUp(self) -> None:
        self.tmp = tempfile.TemporaryDirectory()
        self.root = Path(self.tmp.name)
        run(["git", "init"], self.root).check_returncode()
        run(["git", "config", "user.email", "agent@example.test"], self.root).check_returncode()
        run(["git", "config", "user.name", "Agent"], self.root).check_returncode()

    def tearDown(self) -> None:
        self.tmp.cleanup()

    def commit_file(self, subject: str) -> None:
        target = self.root / "file.txt"
        target.write_text(subject, encoding="utf-8")
        run(["git", "add", "file.txt"], self.root).check_returncode()
        run(["git", "commit", "-m", subject], self.root).check_returncode()

    def test_bug_log_written_under_date_dev_logs_bugs(self) -> None:
        self.commit_file("fix: keep draft preview after save failure")

        result = run(
            [
                sys.executable,
                str(SCRIPT),
                "--kind",
                "bug",
                "--date",
                "2026-06-25",
                "--bug-title",
                "保存草稿失败后表格消失",
                "--bug-slug",
                "draft-preview-disappears",
                "--event",
                "unit test",
                "--no-fetch",
            ],
            self.root,
        )

        self.assertEqual(result.returncode, 0, result.stderr)
        log_path = self.root / "document/development/2026-06-25/dev-logs/bugs/draft-preview-disappears.md"
        content = log_path.read_text(encoding="utf-8")
        self.assertIn("# 保存草稿失败后表格消失", content)
        self.assertIn("## 修复记录", content)
        self.assertIn("Git 提交检查", content)
        self.assertNotIn("## 遗留问题", content)
        self.assertNotIn("## TODO", content)

    def test_auto_skips_non_bug_commit(self) -> None:
        self.commit_file("docs: update development guide")

        result = run([sys.executable, str(SCRIPT), "--kind", "auto", "--date", "2026-06-25", "--no-fetch"], self.root)

        self.assertEqual(result.returncode, 0, result.stderr)
        self.assertIn("skipped_non_bug_commit", result.stdout)
        self.assertFalse((self.root / "document/development/2026-06-25/dev-logs/bugs").exists())

    def test_daily_summary_combines_features_and_bugs(self) -> None:
        feature = self.root / "document/development/2026-06-25/feature/receipt-folder-ocr"
        feature.mkdir(parents=True)
        feature.joinpath("CONCEPT.md").write_text(
            "# 票据夹 OCR 概念文档\n\n## 功能一句话\n\n自动识别票据并生成可核对字段。\n",
            encoding="utf-8",
        )
        feature.joinpath("TODO.md").write_text("- [x] 已完成\n- [ ] 待验证\n", encoding="utf-8")
        bug_dir = self.root / "document/development/2026-06-25/dev-logs/bugs"
        bug_dir.mkdir(parents=True)
        bug_dir.joinpath("draft-preview-disappears.md").write_text(
            "# 保存草稿失败后表格消失\n\n## 修复记录\n\n- 09:30：记录 bug 修复。\n",
            encoding="utf-8",
        )
        self.commit_file("fix: create test commit")

        result = run([sys.executable, str(SCRIPT), "--kind", "summary", "--date", "2026-06-25"], self.root)

        self.assertEqual(result.returncode, 0, result.stderr)
        summary = self.root.joinpath("document/development/2026-06-25/work-logs.med").read_text(encoding="utf-8")
        self.assertIn("# 2026-06-25 综合工作日志", summary)
        self.assertIn("票据夹 OCR 概念文档", summary)
        self.assertIn("保存草稿失败后表格消失", summary)
        self.assertIn("功能侧沉淀了 1 个功能点，问题侧记录了 1 个 bug 修复", summary)


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