from __future__ import annotations

import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from uuid import uuid4

from scripts.repair_software_job_outputs import apply_files, build_plan


class RepairSoftwareJobOutputsTests(unittest.TestCase):
    def test_legacy_directory_moves_and_metadata_becomes_hidden(self) -> None:
        with tempfile.TemporaryDirectory() as directory:
            workspace = Path(directory) / "workspace"
            user_id = uuid4()
            job_id = uuid4()
            user_root = workspace / "users" / str(user_id)
            working_dir = user_root / "模拟计算"
            legacy = user_root / "workspace" / "users" / str(user_id) / "模拟计算" / "origin" / str(job_id)
            legacy.mkdir(parents=True)
            (legacy / "figure.svg").write_text("<svg/>", encoding="utf-8")
            (legacy / "plot-spec.json").write_text("{}", encoding="utf-8")
            job = SimpleNamespace(
                job_id=job_id,
                user_id=user_id,
                artifact_manifest=[{
                    "source_artifact_id": "plot_spec",
                    "filename": "plot-spec.json",
                }],
            )
            task = SimpleNamespace(
                working_dir=f"workspace/users/{user_id}/模拟计算"
            )

            with patch(
                "scripts.repair_software_job_outputs.from_db_path",
                return_value=working_dir,
            ):
                plan = build_plan(job, task)
            self.assertIsNotNone(plan)
            self.assertTrue(plan.move_legacy_dir)
            apply_files(plan)

            target = working_dir / "origin" / str(job_id)
            self.assertTrue((target / "figure.svg").is_file())
            self.assertTrue((target / ".meta" / "plot-spec.json").is_file())
            self.assertFalse(legacy.exists())


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