from __future__ import annotations

import json
import unittest
from pathlib import Path

from mais_humana.cli import main
from mais_humana.workspace_hygiene import (
    HygieneStatus,
    HygieneTarget,
    build_workspace_hygiene_report,
    hygiene_csv,
    hygiene_markdown,
    run_workspace_hygiene,
    safe_child_path,
)
from tests.helpers import make_tmp


class WorkspaceHygieneTests(unittest.TestCase):
    def make_project_with_artifacts(self) -> Path:
        project = make_tmp()
        scratch = project / ".test-tmp" / "case"
        deps = project / "node_modules" / "pkg"
        scratch.mkdir(parents=True)
        deps.mkdir(parents=True)
        (scratch / "evidence.tmp").write_text("temporary evidence", encoding="utf-8")
        (deps / "package.json").write_text("{}", encoding="utf-8")
        return project

    def test_safe_child_path_rejects_escape(self) -> None:
        project = make_tmp()
        with self.assertRaises(ValueError):
            safe_child_path(project, "..\\outside")

    def test_dry_run_reports_present_artifacts_without_deleting(self) -> None:
        project = self.make_project_with_artifacts()
        report = build_workspace_hygiene_report(project, apply=False)
        self.assertEqual(report.status, HygieneStatus.PARTIAL)
        self.assertFalse(report.clean)
        self.assertTrue((project / ".test-tmp").exists())
        self.assertTrue((project / "node_modules").exists())
        self.assertIn("dry run", hygiene_markdown(report))
        self.assertIn("target_id,path,action,status", hygiene_csv(report))

    def test_apply_removes_approved_artifacts(self) -> None:
        project = self.make_project_with_artifacts()
        report = build_workspace_hygiene_report(project, apply=True)
        self.assertEqual(report.status, HygieneStatus.PASSED)
        self.assertTrue(report.clean)
        self.assertFalse((project / ".test-tmp").exists())
        self.assertFalse((project / "node_modules").exists())
        self.assertTrue(all(action.deleted for action in report.actions))

    def test_custom_unsafe_target_is_blocked_before_delete(self) -> None:
        project = make_tmp()
        target = HygieneTarget("unsafe", "..\\outside", "unit test")
        report = build_workspace_hygiene_report(project, apply=True, targets=(target,))
        self.assertEqual(report.status, HygieneStatus.BLOCKED)
        self.assertTrue(report.blockers)
        self.assertIn("escapes project root", report.actions[0].error)

    def test_run_workspace_hygiene_writes_project_and_central_artifacts(self) -> None:
        project = self.make_project_with_artifacts()
        central = make_tmp() / "central" / "15_repo_tudo-para-ia-mais-humana-platform"
        report, records = run_workspace_hygiene(project_root=project, central_platform_folder=central, apply=True)
        self.assertEqual(report.status, HygieneStatus.PASSED)
        self.assertTrue((project / "dados" / "workspace-hygiene-report.json").exists())
        self.assertTrue((project / "matrizes" / "workspace-hygiene-targets.csv").exists())
        self.assertTrue((project / "ecossistema" / "WORKSPACE-HYGIENE-REPORT.md").exists())
        self.assertTrue((central / "reports" / "EXECUTADO__workspace-hygiene.md").exists())
        self.assertGreaterEqual(len(records), 4)

    def test_cli_workspace_hygiene_writes_json_payload(self) -> None:
        project = self.make_project_with_artifacts()
        code = main(["workspace-hygiene", "--project-root", str(project), "--apply"])
        self.assertEqual(code, 0)
        payload = json.loads((project / "dados" / "workspace-hygiene-report.json").read_text(encoding="utf-8"))
        self.assertEqual(payload["status"], "passed")
        self.assertEqual(payload["clean"], True)


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