from __future__ import annotations

import json
import unittest

from mais_humana.cli import main
from mais_humana.storage import table_counts
from mais_humana.workspace_hygiene_policy import (
    HygieneErrorKind,
    HygieneExecutionMode,
    HygienePolicyStatus,
    build_hygiene_policy_report,
    build_policy_cases,
    policy_payload,
)
from tests.helpers import make_tmp


class WorkspaceHygienePolicyTests(unittest.TestCase):
    def test_runtime_policy_contains_acl_owner_cases(self) -> None:
        report = build_hygiene_policy_report(use_generated=False)

        self.assertGreaterEqual(report.cases_count, 1000)
        self.assertGreater(report.owner_action_count, 0)
        self.assertGreater(report.unsafe_block_count, 0)
        self.assertTrue(
            any(
                case.error_kind == HygieneErrorKind.PERMISSION_DENIED
                and case.execution_mode == HygieneExecutionMode.APPLY
                and case.status == HygienePolicyStatus.OWNER_ACTION_REQUIRED
                for case in report.cases
            )
        )

    def test_payload_is_limited_but_keeps_totals(self) -> None:
        report = build_hygiene_policy_report(use_generated=False)
        payload = policy_payload(report, limit_cases=7)

        self.assertEqual(len(payload["cases"]), 7)
        self.assertEqual(payload["cases_total"], report.cases_count)
        self.assertIn("traceId", payload["transit_fields"])

    def test_generated_policy_matches_runtime_case_count(self) -> None:
        runtime_count = len(build_policy_cases())
        generated = build_hygiene_policy_report(use_generated=True)

        self.assertEqual(generated.cases_count, runtime_count)

    def test_cli_writes_policy_artifacts_and_sql(self) -> None:
        project = make_tmp()
        code = main(["workspace-hygiene-policy", "--project-root", str(project), "--no-generated", "--limit", "5"])

        self.assertEqual(code, 0)
        self.assertTrue((project / "dados" / "workspace-hygiene-policy.json").exists())
        self.assertTrue((project / "matrizes" / "workspace-hygiene-policy-cases.csv").exists())
        self.assertTrue((project / "ecossistema" / "WORKSPACE-HYGIENE-POLICY.md").exists())
        payload = json.loads((project / "dados" / "workspace-hygiene-policy.json").read_text(encoding="utf-8"))
        self.assertGreaterEqual(payload["cases_total"], 1000)
        self.assertGreaterEqual(table_counts(project / "controle-semantico.sqlite").get("files", 0), 3)


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

