"""Fake process contract tests only: no model, EasyNet or network invocation."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest


ENTRY = Path(__file__).with_name("agent_entry.py")


class EntryTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory(prefix="teammate-agent-test-")
        self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name)
        self.project = self.root / "existing project"
        self.project.mkdir()
        (self.project / "CLAUDE.md").write_text("Synthetic reviewed rules only", encoding="utf-8")
        (self.project / ".env").write_text("TEAM_DOTENV_MUST_NOT_LOAD=secret\n", encoding="utf-8")
        self.mcp = self.root / "reviewed mcp.json"
        self.mcp.write_text('{"mcpServers": {}}', encoding="utf-8")
        self.binary = self.root / "fake claude"
        self.binary.write_text(
            "#!" + sys.executable + "\n"
            "import json, os, sys\n"
            "print(json.dumps({'argv': sys.argv[1:], 'cwd': os.getcwd(), "
            "'stdin': sys.stdin.read(), 'dotenv': os.getenv('TEAM_DOTENV_MUST_NOT_LOAD')}))\n"
            "print('fake diagnostic', file=sys.stderr)\n"
            "sys.exit(int(os.getenv('TEAM_TEST_EXIT', '0')))\n", encoding="utf-8")
        self.binary.chmod(0o700)
        self.config = {"claude_binary": str(self.binary), "workspace": str(self.project),
                       "mcp_config": str(self.mcp), "model": "test-model",
                       "reviewed_for_shared_synthetic_data": True}
        self.config_path = self.root / "provider.json"

    def run_entry(self, *args, exit_code=0):
        self.config_path.write_text(json.dumps(self.config), encoding="utf-8")
        env = dict(os.environ)
        env.pop("TEAM_DOTENV_MUST_NOT_LOAD", None)
        env["TEAM_TEST_EXIT"] = str(exit_code)
        return subprocess.run([sys.executable, str(ENTRY), "--config", str(self.config_path), *args],
                              input="合成报价\n$(do-not-execute); --resume test\n", text=True,
                              capture_output=True, timeout=5, env=env)

    def test_exact_argv_cwd_stdin_stdout_and_no_dotenv(self):
        result = self.run_entry()
        self.assertEqual(result.returncode, 0, result.stderr)
        output = json.loads(result.stdout)
        self.assertEqual(output["cwd"], str(self.project.resolve()))
        self.assertEqual(output["stdin"], "合成报价\n$(do-not-execute); --resume test\n")
        self.assertIsNone(output["dotenv"])
        self.assertEqual(output["argv"], ["-p", "--output-format", "text", "--permission-mode",
            "dontAsk", "--tools", "Read,Glob,Grep", "--mcp-config", str(self.mcp.resolve()),
            "--strict-mcp-config", "--no-session-persistence", "--max-turns", "8", "--model", "test-model"])
        self.assertEqual(result.stderr, "fake diagnostic\n")

    def test_nonzero_exit_is_preserved(self):
        self.assertEqual(self.run_entry(exit_code=17).returncode, 17)

    def test_check_never_executes(self):
        result = self.run_entry("--check", exit_code=17)
        self.assertEqual(result.returncode, 0)
        self.assertNotIn("fake diagnostic", result.stderr)

    def test_missing_and_relative_paths_fail_before_launch(self):
        for key in ("claude_binary", "workspace", "mcp_config"):
            original = self.config[key]
            for value in (str(self.root / "missing"), "relative/path"):
                with self.subTest(key=key, value=value):
                    self.config[key] = value
                    result = self.run_entry()
                    self.assertEqual(result.returncode, 2)
                    self.assertEqual(result.stdout, "")
            self.config[key] = original

    def test_missing_instructions(self):
        (self.project / "CLAUDE.md").unlink()
        self.assertEqual(self.run_entry().returncode, 2)

    def test_review_required_and_unknown_options_rejected(self):
        for value in (False, "true", 1, None):
            self.config["reviewed_for_shared_synthetic_data"] = value
            self.assertEqual(self.run_entry().returncode, 2)
        self.config["reviewed_for_shared_synthetic_data"] = True
        self.config["extra_args"] = ["--dangerously-skip-permissions"]
        self.assertEqual(self.run_entry().returncode, 2)

    def test_invalid_mcp_and_nonexecutable(self):
        self.mcp.write_text("{}", encoding="utf-8")
        self.assertEqual(self.run_entry().returncode, 2)
        self.mcp.write_text('{"mcpServers": {}}', encoding="utf-8")
        self.binary.chmod(0o600)
        self.assertEqual(self.run_entry().returncode, 2)

    def test_no_config_and_invalid_json(self):
        result = subprocess.run([sys.executable, str(ENTRY)], capture_output=True, timeout=5)
        self.assertEqual(result.returncode, 2)
        self.mcp.write_text("invalid json", encoding="utf-8")
        self.assertEqual(self.run_entry().returncode, 2)


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