"""
C4 — Definitional consistency.

Checks for cycles in the dependency graph and definitional conflicts
between entities.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, List, Optional

from markitect.infospace.models import EntityMeta
from markitect.prompts.dependencies.models import DependencyGraph


@dataclass
class ConsistencyReport:
    """Results from consistency analysis."""

    cycles: List[List[str]] = field(default_factory=list)
    cycle_count: int = 0
    entity_count: int = 0

    def to_dict(self) -> dict:
        return {
            "concern": "C4",
            "cycle_count": self.cycle_count,
            "cycles": self.cycles,
            "entity_count": self.entity_count,
        }


def check_consistency(
    entities: List[EntityMeta],
    graph: Optional[DependencyGraph] = None,
) -> ConsistencyReport:
    """Check definitional consistency.

    Args:
        entities: Entity metadata list.
        graph: Optional dependency graph for cycle detection.

    Returns:
        :class:`ConsistencyReport` with cycles found.
    """
    n = len(entities)
    cycles: List[List[str]] = []

    if graph is not None and len(graph.nodes) > 0:
        raw_cycles = graph.detect_cycles()
        cycles = raw_cycles

    return ConsistencyReport(
        cycles=cycles,
        cycle_count=len(cycles),
        entity_count=n,
    )
