from __future__ import annotations

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

ROOT = Path(__file__).resolve().parents[1]
FIX_IN = ROOT / "tests" / "fixtures" / "in"


def run_cli(args: list[str], env: dict[str, str]) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [sys.executable, "-m", "doc2md.cli", *args],
        cwd=ROOT,
        text=True,
        capture_output=True,
        env=env,
    )


class RecentCommandTest(unittest.TestCase):
    def test_recent_inputs_and_projects_json(self) -> None:
        input_one = FIX_IN / "sample.csv"
        input_two = FIX_IN / "edge.csv"
        with tempfile.TemporaryDirectory() as tmpdir:
            db_path = Path(tmpdir) / "history.db"
            out1 = Path(tmpdir) / "out1.md"
            out2 = Path(tmpdir) / "out2.md"
            env = os.environ.copy()
            env["DOC2MD_HISTORY_DB"] = str(db_path)

            first = run_cli([str(input_one), "-o", str(out1), "--quiet"], env)
            second = run_cli([str(input_two), "-o", str(out2), "--quiet"], env)
            self.assertEqual(first.returncode, 0)
            self.assertEqual(second.returncode, 0)

            recent = run_cli(["recent", "--json"], env)
            self.assertEqual(recent.returncode, 0)
            payload = json.loads(recent.stdout)
            self.assertIn("inputs", payload)
            self.assertIn("projects", payload)
            input_paths = {item["path"] for item in payload["inputs"]}
            self.assertIn(str(input_one), input_paths)
            self.assertIn(str(input_two), input_paths)
            self.assertEqual(payload["projects"][0]["path"], str(FIX_IN))
            self.assertEqual(payload["projects"][0]["count"], 2)


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