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], cwd: Path) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [sys.executable, "-m", "doc2md.cli", *args],
        cwd=cwd,
        text=True,
        capture_output=True,
        env=env,
    )


class JumpCommandTest(unittest.TestCase):
    def test_jump_returns_most_frequent(self) -> None:
        with tempfile.TemporaryDirectory() as tmpdir:
            temp_path = Path(tmpdir)
            db_path = temp_path / "history.db"
            env = os.environ.copy()
            env["DOC2MD_HISTORY_DB"] = str(db_path)
            env["PYTHONPATH"] = str(ROOT)

            out1 = temp_path / "out1.md"
            out2 = temp_path / "out2.md"
            out3 = temp_path / "out3.md"
            run_cli([str(FIX_IN / "sample.csv"), "-o", str(out1), "--quiet", "--yes"], env, ROOT)
            run_cli([str(FIX_IN / "sample.csv"), "-o", str(out2), "--quiet", "--yes"], env, ROOT)
            run_cli([str(FIX_IN / "edge.csv"), "-o", str(out3), "--quiet", "--yes"], env, ROOT)

            result = run_cli(["jump", "sample", "--json"], env, ROOT)
            self.assertEqual(result.returncode, 0)
            items = json.loads(result.stdout)
            self.assertTrue(items)
            self.assertIn("sample.csv", items[0]["path"])
            self.assertEqual(items[0]["count"], 2)

            top = run_cli(["jump", "--json"], env, ROOT)
            top_items = json.loads(top.stdout)
            self.assertIn("sample.csv", top_items[0]["path"])

    def test_jump_missing_history(self) -> None:
        with tempfile.TemporaryDirectory() as tmpdir:
            temp_path = Path(tmpdir)
            env = os.environ.copy()
            env["DOC2MD_HISTORY_DB"] = str(temp_path / "missing.db")
            env["PYTHONPATH"] = str(ROOT)
            result = run_cli(["jump", "sample"], env, ROOT)
            self.assertEqual(result.returncode, 2)
            self.assertIn("History database not found", result.stderr)


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