from __future__ import annotations

import unittest

from mais_humana.repository_mesh import MeshEnvironment, MeshEnvironmentKind, RepositoryTarget, build_mesh_report
from mais_humana.repository_mesh_gitea import (
    GiteaAuth,
    GiteaPlannedAction,
    GiteaRepoStatus,
    build_gitea_mesh_plan,
    classify_http_error,
    endpoint_for_target,
    gitea_plan_csv,
    gitea_plan_markdown,
    plan_for_target,
    write_gitea_plan_artifacts,
)
from tests.helpers import make_tmp
from tests.test_repository_mesh import FakeGit, make_repo


class RepositoryMeshGiteaTests(unittest.TestCase):
    def test_endpoint_for_target_builds_api_and_clone_urls(self) -> None:
        target = RepositoryTarget("alpha", "admin/alpha", "alpha", "01_alpha")
        endpoint = endpoint_for_target(target)
        self.assertEqual(endpoint.api_repo_path, "/api/v1/repos/admin/alpha")
        self.assertEqual(endpoint.clone_url, "https://git.ami.app.br/admin/alpha.git")

    def test_auth_headers_are_redacted_and_support_token_or_basic(self) -> None:
        token = GiteaAuth(token="secret")
        self.assertIn("Authorization", token.headers())
        self.assertEqual(token.redacted_label(), "token:<redacted>")
        basic = GiteaAuth(username="ami", password="pw")
        self.assertIn("Authorization", basic.headers())
        self.assertEqual(basic.redacted_label(), "basic:ami:<redacted>")

    def test_http_error_classifier_maps_common_statuses(self) -> None:
        self.assertEqual(classify_http_error(200), GiteaRepoStatus.EXISTS)
        self.assertEqual(classify_http_error(404), GiteaRepoStatus.MISSING)
        self.assertEqual(classify_http_error(401), GiteaRepoStatus.UNAUTHORIZED)
        self.assertEqual(classify_http_error(403), GiteaRepoStatus.FORBIDDEN)
        self.assertEqual(classify_http_error(None, "network"), GiteaRepoStatus.NETWORK_ERROR)

    def test_plan_for_missing_repo_requires_token_and_create_action(self) -> None:
        target = RepositoryTarget("alpha", "admin/alpha", "alpha", "01_alpha")
        endpoint = endpoint_for_target(target)
        plan = plan_for_target(target, endpoint=endpoint, status=GiteaRepoStatus.MISSING, auth=GiteaAuth())
        self.assertTrue(plan.blocked)
        self.assertIn(GiteaPlannedAction.REQUIRE_TOKEN, plan.actions)
        self.assertIn(GiteaPlannedAction.CREATE_REPOSITORY, plan.actions)
        self.assertTrue(plan.api_requests)

    def test_nominal_reconciliation_target_requires_owner_decision(self) -> None:
        target = RepositoryTarget(
            "alpha-plataform",
            "admin/alpha",
            "alpha-plataform",
            "01_alpha",
            aliases=("alpha",),
            canonical_name="alpha-plataform",
            requires_nominal_reconciliation=True,
        )
        plan = plan_for_target(target, endpoint=endpoint_for_target(target), status=GiteaRepoStatus.EXISTS, auth=GiteaAuth(token="x"))
        self.assertIn(GiteaPlannedAction.REQUIRE_OWNER_DECISION, plan.actions)
        self.assertIn(GiteaPlannedAction.RENAME_REPOSITORY, plan.actions)

    def test_build_gitea_mesh_plan_infers_status_from_mesh_report(self) -> None:
        tmp = make_tmp()
        repo = make_repo(tmp, "alpha")
        fake = FakeGit()
        fake.set_repo(repo, remote="https://git.ami.app.br/admin/alpha.git")
        target = RepositoryTarget("alpha", "admin/alpha", "alpha", "01_alpha")
        env = MeshEnvironment("primary", MeshEnvironmentKind.WINDOWS_PRIMARY, str(tmp), "test")
        report = build_mesh_report(tmp, targets=(target,), environments=(env,), runner=fake)
        plan = build_gitea_mesh_plan(report)
        self.assertEqual(plan.exists_count, 1)
        self.assertEqual(plan.blocked_count, 1)
        self.assertEqual(plan.repositories[0].status, GiteaRepoStatus.EXISTS)

    def test_gitea_renderers_and_artifacts_are_written(self) -> None:
        tmp = make_tmp()
        project = tmp / "project"
        central = tmp / "central"
        project.mkdir()
        central.mkdir()
        target = RepositoryTarget("alpha", "admin/alpha", "alpha", "01_alpha")
        endpoint = endpoint_for_target(target)
        repo_plan = plan_for_target(target, endpoint=endpoint, status=GiteaRepoStatus.MISSING, auth=GiteaAuth())
        from mais_humana.repository_mesh_gitea import GiteaMeshPlan

        plan = GiteaMeshPlan("plan-1", "2026-01-01T00:00:00+00:00", "https://git.ami.app.br", "none", (repo_plan,))
        self.assertIn("plan_id,declared_name", gitea_plan_csv(plan))
        self.assertIn("Gitea Repository Mesh Plan", gitea_plan_markdown(plan))
        records = write_gitea_plan_artifacts(plan, project, central_platform_folder=central)
        self.assertTrue((project / "dados" / "repository-mesh-gitea-plan.json").exists())
        self.assertTrue((project / "ecossistema" / "REPOSITORY-MESH-GITEA.md").exists())
        self.assertTrue((central / "reports" / "PENDENCIAS-CODEX__repository-mesh-gitea.md").exists())
        self.assertGreaterEqual(len(records), 4)


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