from __future__ import annotations

import sqlite3
import unittest

from mais_humana.repository_mesh import MeshEnvironment, MeshEnvironmentKind, RepositoryTarget, build_mesh_report
from mais_humana.repository_mesh_reconciliation import build_reconciliation_plan
from mais_humana.repository_mesh_runtime import acquire_lock, build_runtime_cycle, cron_scheduler_spec, release_lock, windows_scheduler_spec
from mais_humana.repository_mesh_semantic import counts_markdown, semantic_generated_records, table_counts, write_repository_mesh_semantic_state
from tests.helpers import make_tmp
from tests.test_repository_mesh import FakeGit, make_repo


class RepositoryMeshSemanticTests(unittest.TestCase):
    def build_objects(self):
        tmp = make_tmp()
        eco = tmp / "eco"
        project = tmp / "project"
        eco.mkdir()
        project.mkdir()
        repo = make_repo(eco, "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(eco), "test")
        report = build_mesh_report(eco, targets=(target,), environments=(env,), runner=fake)
        plan = build_reconciliation_plan(report)
        lock = acquire_lock(project / "dados" / "lock.json", owner="semantic-test")
        cycle = build_runtime_cycle(report, plan, lock=lock)
        specs = (
            windows_scheduler_spec(python_exe="python.exe", project_root=project, ecosystem_root=eco, central_platform_folder=None),
            cron_scheduler_spec(python_exe="python", project_root=project, ecosystem_root=eco, central_platform_folder=None),
        )
        return tmp, report, plan, cycle, specs, lock

    def test_write_repository_mesh_semantic_state_populates_tables(self) -> None:
        tmp, report, plan, cycle, specs, lock = self.build_objects()
        sqlite_path = tmp / "central" / "controle-semantico.sqlite"
        counts = write_repository_mesh_semantic_state(sqlite_path, report=report, plan=plan, cycle=cycle, schedulers=specs)
        self.assertEqual(counts.reports, 1)
        self.assertEqual(counts.targets, 1)
        self.assertEqual(counts.observations, 1)
        self.assertGreaterEqual(counts.actions, 1)
        self.assertEqual(counts.plans, 1)
        self.assertEqual(counts.receipts, 1)
        self.assertEqual(counts.cycles, 1)
        self.assertEqual(counts.schedulers, 2)
        release_lock(lock)

    def test_semantic_state_is_idempotent_for_same_report_and_plan(self) -> None:
        tmp, report, plan, cycle, specs, lock = self.build_objects()
        sqlite_path = tmp / "central" / "controle-semantico.sqlite"
        first = write_repository_mesh_semantic_state(sqlite_path, report=report, plan=plan, cycle=cycle, schedulers=specs)
        second = write_repository_mesh_semantic_state(sqlite_path, report=report, plan=plan, cycle=cycle, schedulers=specs)
        self.assertEqual(first.to_dict(), second.to_dict())
        with sqlite3.connect(sqlite_path) as conn:
            rows = conn.execute("SELECT report_id, blocked_count FROM repository_mesh_reports").fetchall()
        self.assertEqual(len(rows), 1)
        self.assertEqual(rows[0][0], report.report_id)
        release_lock(lock)

    def test_table_counts_for_missing_database_returns_zeroes(self) -> None:
        counts = table_counts(make_tmp() / "missing.sqlite")
        self.assertEqual(counts.reports, 0)
        self.assertEqual(counts.schedulers, 0)

    def test_semantic_generated_records_and_markdown_are_human_readable(self) -> None:
        sqlite_path = make_tmp() / "central" / "controle-semantico.sqlite"
        records = semantic_generated_records(sqlite_path)
        self.assertEqual(len(records), 1)
        self.assertIn("repository mesh semantic", records[0].function)
        text = counts_markdown(table_counts(sqlite_path), sqlite_path)
        self.assertIn("Repository Mesh Semantic Counts", text)
        self.assertIn("reports", text)


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