import tempfile
import unittest
from pathlib import Path

from tools.run_python import RunPythonTool


class RunPythonScriptPathTests(unittest.TestCase):
    def test_executes_existing_script_path(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            script = Path(tmp) / "hello.py"
            script.write_text("print('hello from file')\n", encoding="utf-8")

            out = RunPythonTool(base_dir=tmp).execute(script_path="hello.py")

        self.assertIn("[stdout]\nhello from file", out)
        self.assertIn("[exit 0]", out)

    def test_requires_code_or_script_path(self) -> None:
        out = RunPythonTool().execute()

        self.assertIn("[Error]", out)
        self.assertIn("code or script_path", out)

    def test_missing_script_path_errors_with_hint(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            out = RunPythonTool(base_dir=tmp).execute(script_path="scripts/nope.py")

        self.assertIn("script_path not found", out)
        self.assertIn("write", out)

    def test_code_saved_to_missing_script_path_then_executed(self) -> None:
        """code + script_path 同给且文件不存在 → code 落盘到 script_path 再执行(0.58.22)。"""
        with tempfile.TemporaryDirectory() as tmp:
            out = RunPythonTool(base_dir=tmp).execute(
                script_path="scripts/gen.py", code="print('saved-and-run')"
            )
            saved = Path(tmp) / "scripts" / "gen.py"
            self.assertTrue(saved.is_file())
            self.assertEqual(saved.read_text(encoding="utf-8"), "print('saved-and-run')")

        self.assertIn("[stdout]\nsaved-and-run", out)
        self.assertIn("[exit 0]", out)

    def test_existing_script_path_wins_over_code(self) -> None:
        """文件已存在时 script_path 优先,code 不覆盖已有文件。"""
        with tempfile.TemporaryDirectory() as tmp:
            script = Path(tmp) / "job.py"
            script.write_text("print('from file')\n", encoding="utf-8")

            out = RunPythonTool(base_dir=tmp).execute(
                script_path="job.py", code="print('from code')"
            )
            self.assertEqual(
                script.read_text(encoding="utf-8"), "print('from file')\n"
            )

        self.assertIn("[stdout]\nfrom file", out)

    def test_user_root_relative_fallback(self) -> None:
        """路径带工作目录名前缀(fs 工具输出的 user_root 相对形态)→ 容错解析。"""
        with tempfile.TemporaryDirectory() as tmp:
            user_root = Path(tmp)
            task_dir = user_root / "demo"
            script = task_dir / "scripts" / "job.py"
            script.parent.mkdir(parents=True)
            script.write_text("print('fallback ok')\n", encoding="utf-8")

            out = RunPythonTool(base_dir=task_dir, user_root=user_root).execute(
                script_path="demo/scripts/job.py"
            )

        self.assertIn("[stdout]\nfallback ok", out)
        self.assertIn("[exit 0]", out)


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