from __future__ import annotations

import json
import unittest

from mais_humana.canonical_identity import (
    CANONICAL_PROJECT_ID,
    CURRENT_PROJECT_ID,
    LEGACY_PLATAFORM_ALIAS,
    IdentityIssueSeverity,
    build_identity_graph,
    identity_acceptance_rows,
    identity_graph_markdown,
    identity_graph_payload,
    validate_identity_payload,
)
from mais_humana.cli import main
from tests.helpers import make_tmp


class CanonicalIdentityTests(unittest.TestCase):
    def test_graph_accepts_canonical_current_and_plataform_alias(self) -> None:
        graph = build_identity_graph(use_generated=False)

        self.assertEqual(graph.canonicalize(CURRENT_PROJECT_ID), CANONICAL_PROJECT_ID)
        self.assertEqual(graph.canonicalize(LEGACY_PLATAFORM_ALIAS), CANONICAL_PROJECT_ID)
        self.assertEqual(graph.canonicalize(CANONICAL_PROJECT_ID), CANONICAL_PROJECT_ID)

        record = graph.record_for(CURRENT_PROJECT_ID)
        self.assertIsNotNone(record)
        self.assertEqual(record.canonical_project_id if record else "", CANONICAL_PROJECT_ID)
        self.assertIn("Canonical Identity Graph", identity_graph_markdown(graph))

    def test_payload_validation_warns_for_alias_in_canonical_field(self) -> None:
        graph = build_identity_graph(use_generated=False)
        result = validate_identity_payload(
            {
                "ownerPlatformId": CURRENT_PROJECT_ID,
                "projectId": LEGACY_PLATAFORM_ALIAS,
                "canonicalProjectId": CANONICAL_PROJECT_ID,
            },
            graph=graph,
        )

        self.assertTrue(result.ok)
        self.assertIn(CANONICAL_PROJECT_ID, result.canonical_project_ids)
        self.assertIn(CURRENT_PROJECT_ID, result.accepted_aliases)
        self.assertTrue(any(issue.severity == IdentityIssueSeverity.WARNING for issue in result.issues))

    def test_payload_validation_blocks_unknown_identifier(self) -> None:
        result = validate_identity_payload({"ownerPlatformId": "repo-inexistente"}, graph=build_identity_graph(use_generated=False))

        self.assertFalse(result.ok)
        self.assertEqual(result.blockers[0].severity, IdentityIssueSeverity.BLOCKER)

    def test_generated_registry_has_mcp_acceptance_cases(self) -> None:
        graph = build_identity_graph(use_generated=True)
        rows = identity_acceptance_rows(graph)
        payload = identity_graph_payload(graph, limit_cases=3)

        self.assertGreaterEqual(graph.records_count, 15)
        self.assertGreaterEqual(len(graph.acceptance_cases), 4000)
        self.assertEqual(payload["maisHumanaCanonicalProjectId"], CANONICAL_PROJECT_ID)
        self.assertIn("ownerPlatformId", {row[4] for row in rows[1:100]})

    def test_cli_writes_identity_graph_artifacts(self) -> None:
        root = make_tmp()
        project = root / "tudo-para-ia-mais-humana"
        central = root / "central" / "15_repo_tudo-para-ia-mais-humana-platform"

        code = main(
            [
                "canonical-identity",
                "--project-root",
                str(project),
                "--central-platform-folder",
                str(central),
                "--no-generated",
            ]
        )

        self.assertEqual(code, 0)
        graph_json = project / "dados" / "canonical-identity-graph.json"
        self.assertTrue(graph_json.exists())
        self.assertTrue((project / "matrizes" / "canonical-identity-graph.csv").exists())
        self.assertTrue((project / "matrizes" / "canonical-identity-acceptance-cases.csv").exists())
        self.assertTrue((project / "ecossistema" / "CANONICAL-IDENTITY-GRAPH.md").exists())
        self.assertTrue((central / "reports" / "EXECUTADO__canonical-identity-graph.md").exists())
        payload = json.loads(graph_json.read_text(encoding="utf-8"))
        self.assertEqual(payload["maisHumanaCanonicalProjectId"], CANONICAL_PROJECT_ID)


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