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]


def run_cli(args: list[str], cwd: Path) -> subprocess.CompletedProcess[str]:
    env = os.environ.copy()
    existing = env.get("PYTHONPATH")
    if existing:
        env["PYTHONPATH"] = f"{ROOT}{os.pathsep}{existing}"
    else:
        env["PYTHONPATH"] = str(ROOT)
    return subprocess.run(
        [sys.executable, "-m", "doc2md.cli", *args],
        cwd=cwd,
        text=True,
        capture_output=True,
        env=env,
    )


class ProfileCommandTest(unittest.TestCase):
    def test_profile_list_and_show_json(self) -> None:
        with tempfile.TemporaryDirectory() as tmpdir:
            temp_path = Path(tmpdir)
            (temp_path / "doc2md.toml").write_text(
                "\n".join(
                    [
                        "[profiles.default]",
                        "format = \"csv\"",
                        "",
                        "[profiles.fast]",
                        "engine = \"pdftext\"",
                        "quiet = true",
                        "",
                    ]
                ),
                encoding="utf-8",
            )

            result = run_cli(["profile", "list", "--json"], temp_path)
            self.assertEqual(result.returncode, 0)
            names = json.loads(result.stdout)
            self.assertEqual(names, ["default", "fast"])

            show = run_cli(["profile", "show", "fast", "--json"], temp_path)
            self.assertEqual(show.returncode, 0)
            profile = json.loads(show.stdout)
            self.assertEqual(profile["engine"], "pdftext")
            self.assertTrue(profile["quiet"])

    def test_profile_missing_file_exit_2(self) -> None:
        with tempfile.TemporaryDirectory() as tmpdir:
            temp_path = Path(tmpdir)
            result = run_cli(["profile", "list"], temp_path)
            self.assertEqual(result.returncode, 2)
            self.assertIn("Profile file not found", result.stderr)

    def test_profile_apply_merges_defaults(self) -> None:
        with tempfile.TemporaryDirectory() as tmpdir:
            temp_path = Path(tmpdir)
            (temp_path / "doc2md.toml").write_text(
                "\n".join(
                    [
                        "[profiles.default]",
                        "format = \"csv\"",
                        "csv_na = \"NA\"",
                        "",
                        "[profiles.fast]",
                        "engine = \"pdftext\"",
                        "quiet = true",
                        "",
                    ]
                ),
                encoding="utf-8",
            )
            result = run_cli(["profile", "apply", "fast", "--json"], temp_path)
            self.assertEqual(result.returncode, 0)
            merged = json.loads(result.stdout)
            self.assertEqual(merged["format"], "csv")
            self.assertEqual(merged["csv_na"], "NA")
            self.assertEqual(merged["engine"], "pdftext")
            self.assertTrue(merged["quiet"])


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