from __future__ import annotations

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


class ConfigPathsResolutionTest(unittest.TestCase):
    def setUp(self):
        self.repo_root = Path(__file__).resolve().parents[1]

    def _load_paths(self, *, cwd: Path, extra_env: dict | None = None) -> dict:
        code = """
import json
import config
print(json.dumps({
  "DEFAULT_PROJECT_PATH": config.DEFAULT_PROJECT_PATH,
  "HOST_WORKSPACES_FILE": config.HOST_WORKSPACES_FILE,
  "DATA_DIR": config.DATA_DIR,
  "LOGS_DIR": config.LOGS_DIR,
  "USER_SPACE_DIR": config.USER_SPACE_DIR,
  "API_USER_SPACE_DIR": config.API_USER_SPACE_DIR,
  "SUB_AGENT_STATE_FILE": config.SUB_AGENT_STATE_FILE,
}, ensure_ascii=False))
"""
        env = dict(os.environ)
        env["PYTHONPATH"] = str(self.repo_root)
        if extra_env:
            env.update(extra_env)
        completed = subprocess.run(
            [sys.executable, "-c", code],
            cwd=str(cwd),
            env=env,
            capture_output=True,
            text=True,
            check=True,
        )
        lines = [line.strip() for line in (completed.stdout or "").splitlines() if line.strip()]
        self.assertTrue(lines, f"stdout is empty, stderr={completed.stderr}")
        return json.loads(lines[-1])

    def test_default_paths_are_resolved_from_repo_root(self):
        with tempfile.TemporaryDirectory() as td:
            data = self._load_paths(cwd=Path(td))

        for key, raw in data.items():
            value = Path(str(raw))
            self.assertTrue(value.is_absolute(), f"{key} is not absolute: {raw}")
            self.assertTrue(
                str(value).startswith(str(self.repo_root)),
                f"{key} should be anchored to repo root: {raw}",
            )

    def test_relative_env_overrides_also_anchor_to_repo_root(self):
        with tempfile.TemporaryDirectory() as td:
            data = self._load_paths(
                cwd=Path(td),
                extra_env={
                    "DEFAULT_PROJECT_PATH": "./workspace_rel",
                    "DATA_DIR": "./data_rel",
                    "LOGS_DIR": "./logs_rel",
                    "USER_SPACE_DIR": "./users_rel",
                    "HOST_WORKSPACES_FILE": "./config/host_workspaces_rel.json",
                    "SUB_AGENT_STATE_FILE": "./data/sub_agents_rel.json",
                },
            )

        self.assertEqual(data["DEFAULT_PROJECT_PATH"], str((self.repo_root / "workspace_rel").resolve()))
        self.assertEqual(data["DATA_DIR"], str((self.repo_root / "data_rel").resolve()))
        self.assertEqual(data["LOGS_DIR"], str((self.repo_root / "logs_rel").resolve()))
        self.assertEqual(data["USER_SPACE_DIR"], str((self.repo_root / "users_rel").resolve()))
        self.assertEqual(
            data["HOST_WORKSPACES_FILE"],
            str((self.repo_root / "config" / "host_workspaces_rel.json").resolve()),
        )
        self.assertEqual(
            data["SUB_AGENT_STATE_FILE"],
            str((self.repo_root / "data" / "sub_agents_rel.json").resolve()),
        )


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