"""
fol_formalizasyon.axioms — Registry of all framework axioms, theorems, and kavaid.

Contains:
  - 59 defined axioms (AX1–AX66, gaps: AX6–10 unassigned, AX35–36 unassigned)
  - 15 defined theorems (T3–T18, gaps: T1–2 unassigned, T11 index-only)
  - 8 kavaid (KV₁–KV₈)

Per AGENTS.md:
  AX64: Source text immutability — axiom text is frozen
  AX65: Reference pairing — every entry has source_ref
  IG.6: Numbering preserved as-is (AX6–10, AX35–36, T1–2, T11 gaps)

Lookup functions:
  get_axiom(id)            → Axiom or None
  get_theorem(id)          → Theorem or None
  get_kavaid(id)           → Kavaid or None
  axioms_by_layer(layer)   → list[Axiom]
  axioms_by_tag(tag)       → list[Axiom]
  list_all_axioms()        → list[Axiom]
  list_all_theorems()      → list[Theorem]
  list_all_kavaid()        → list[Kavaid]
  defined_axiom_ids()      → set[str]
  gap_axiom_ids()          → set[str]
"""

from .types import Axiom, Theorem, Kavaid


# ---------------------------------------------------------------------------
# GAP REGISTER (AGENTS.md IG.6) — numbering preserved per AX64
# ---------------------------------------------------------------------------

_GAP_AXIOM_IDS = {"AX6", "AX7", "AX8", "AX9", "AX10", "AX35", "AX36"}
_GAP_THEOREM_IDS = {"T1", "T2", "T11"}


# ---------------------------------------------------------------------------
# AXIOM REGISTRY — All 59 defined axioms
# ---------------------------------------------------------------------------

_AXIOM_REGISTRY: dict[str, Axiom] = {}


def _ax(id: str, name: str, axiom_text: str, source_ref: str,
        layer: int, tags: tuple[str, ...] = ()) -> None:
    """Register an axiom in the internal registry."""
    _AXIOM_REGISTRY[id] = Axiom(
        id=id, name=name, formula=None,
        axiom_text=axiom_text, source_ref=source_ref,
        layer=layer, tags=tags,
    )


# ── Layer 1 — Foundational Commitments ──────────────────────────

_ax("AX1", "Ontological Axiom (K₁)",
    "∀x ∈ Being: FormallyOrdered(x) ← Sudur(x, el-Hakîm)",
    "C-005", 1, ("foundational", "modal"))

_ax("AX2", "İlim (Distinguishing)",
    "Mumeyyiz(Ilim): ¬Ilim → ¬Distinction → ¬Structure → ¬Order",
    "C-010", 1, ("foundational", "triad"))

_ax("AX3", "İrade (Specifying)",
    "Muhassıs(Irade): ¬Irade → ¬Selection → ¬Determination → ¬Law",
    "C-011", 1, ("foundational", "triad"))

_ax("AX4", "Kudret (Effecting)",
    "Muessir(Kudret): ¬Kudret → ¬Actualization → ¬Existence",
    "C-012", 1, ("foundational", "triad"))

_ax("AX5", "Hayat (Integration Prerequisite)",
    "¬Hayat → ∀s' ∈ S_Sifat\\{Hayat}: Inert(s')",
    "C-018", 1, ("foundational", "integration"))

_ax("AX11", "Disorder Impossibility",
    "∀s ∈ Sifat_Seba: Perfect(s) → ¬Disorder(reality)",
    "C-021", 1, ("foundational", "order"))

_ax("AX12", "Vahidiyet Containment",
    "All Names held under Vahidiyet (unity-containment)",
    "C-024", 1, ("foundational", "unity"))

_ax("AX13", "Ehadiyet Reflection",
    "Each individual Name reflects all others in each manifestation",
    "C-024", 1, ("foundational", "unity"))

# ── Layer 2 — Ontological Framework ─────────────────────────────

_ax("AX14", "Perfection Propagation (Ascending)",
    "Kemal(Âsâr) = ∞ ⟹ Kemal(Ef'âl) = ∞ ⟹ … ⟹ Kemal(Zât) = ∞",
    "C-028", 2, ("ontological", "quality"))

_ax("AX15", "Leveled Perfection",
    "Mebde(Sıfât) = Şuûnât",
    "C-028", 2, ("ontological", "quality"))

_ax("AX16", "Descending Manifestation",
    "Kemal descends through 5 Perde (veils)",
    "C-029", 2, ("ontological", "quality"))

_ax("AX17", "Hakikat = Esmâ Identity",
    "∀x ∈ S_Mumkin: Hakikat(x) = {n ∈ S_Isim | Tecelli(n, x) > 0}",
    "C-032", 2, ("ontological", "esma"))

_ax("AX18", "Shadow Ontology",
    "Mahiyet(x) = Shadow(Hakikat(x))",
    "C-033", 2, ("ontological", "esma"))

_ax("AX19", "Name Density Lower Bound",
    "∀x ∈ Living: |Hakikat(x)| ≥ 20",
    "C-034", 2, ("ontological", "esma"))

_ax("AX20", "Science-to-Name Grounding",
    "∀science ∈ Domain: ∃n ∈ S_Isim: Istinad(science, n)",
    "C-037", 2, ("ontological", "esma"))

_ax("AX21", "Infinite Degrees",
    "Tecelli(n, x) ∈ ℝ≥₀ (continuous, not binary); ∀n: |Merâtib(n)| = ∞",
    "C-039", 2, ("ontological", "continuous"))

_ax("AX22", "Ekmel / el-Husnâ (Unreachable Supremum)",
    "∀n,w: mertebe(n,w) < ekmel(n) (never attained)",
    "C-040", 2, ("ontological", "continuous", "supremum"))

_ax("AX23", "Cascade Structure",
    "Names form DAG with root in S_Seun; kaskad transitive",
    "C-043", 2, ("ontological", "cascade"))

_ax("AX24", "Self-Love of Beauty",
    "Beauty is intrinsically lovable — no external validation needed",
    "C-045", 2, ("ontological", "cascade"))

_ax("AX25", "Desire-to-Show",
    "Beauty desires to see itself in mirrors",
    "C-045", 2, ("ontological", "cascade"))

_ax("AX26", "Esbab Rationale",
    "Causes exist for Wisdom + multi-Name simultaneous manifestation",
    "C-047", 2, ("ontological", "causes"))

_ax("AX27", "Transparent Vessel Ontology",
    "Causes are transparent vessels (zarf, tablacı), not autonomous agents",
    "C-047", 2, ("ontological", "causes"))

_ax("AX28", "Kudret/Hikmet Polarity",
    "Kemal = Kudret ⊕ Hikmet (complementary, not competing)",
    "C-049", 2, ("ontological", "polarity"))

_ax("AX29", "Nizam/İntizam",
    "CosmicOrder = Nizam ∧ İntizam (quantitative + qualitative)",
    "C-049", 2, ("ontological", "order"))

_ax("AX30", "İmkân = Fakr",
    "◇¬E(x) → Fakr(x)",
    "C-050", 2, ("ontological", "dependency"))

_ax("AX31", "Fakr → Rahmet",
    "Fakr(x) → Response(Rahman, Rahim)(x)",
    "C-050", 2, ("ontological", "dependency"))

_ax("AX32", "Hudûs = Acz",
    "Hadis(x) → Acz(x)",
    "C-052", 2, ("ontological", "dependency"))

_ax("AX33", "Acz → Kudret",
    "Acz(x) → Response(Kadîr)(x)",
    "C-052", 2, ("ontological", "dependency"))

_ax("AX34", "Constitutive Wounds",
    "Fakr(x) ∧ Acz(x) are constitutive (not acquired, not removable)",
    "C-053", 2, ("ontological", "dependency"))

# AX35–AX36: Unassigned numbering gap (IG.6)

_ax("AX37", "Holographic Structure",
    "∀P ⊂ Kur'an: Structure(P) ≅ Structure(Kur'an)",
    "C-057", 2, ("ontological", "holographic"))

_ax("AX38", "Tereşşuhat Ontology",
    "NeAynNeGayr(RisaleINur, Kur'an); Teressuh(RisaleINur, Kur'an)",
    "C-060", 2, ("ontological", "holographic"))

_ax("AX39", "Edeb Prerequisite",
    "ValidMethod → ProperConduct; First act: know your station",
    "C-063", 2, ("ontological", "edeb"))

# ── Layer 3 — Epistemic Architecture ────────────────────────────

_ax("AX40", "70,000 Veils",
    "Vahiy > İlham; İlham hierarchy: Hayvanat < AvamNas < AvamMelaike < Evliya < MelaikeIzam",
    "C-065", 3, ("epistemic", "kelam"))

_ax("AX41", "Vahiy-İlham Gap",
    "∀veli, ∀nebi: Rank(veli) < Rank(nebi)",
    "C-066", 3, ("epistemic", "kelam"))

_ax("AX42", "Risale Station = Sünuhat",
    "Mode(RisaleINur) = Sünuhat",
    "C-067", 3, ("epistemic", "station"))

_ax("AX43", "Project Station = İstidlal",
    "Mode(Formalization) = İstidlal; Lenses = şart-ı âdî",
    "C-068", 3, ("epistemic", "station"))

_ax("AX44", "Külliyat-Tafsîlât Split",
    "Reliability(Külliyat) >> Reliability(Tafsîlât)",
    "C-070", 3, ("epistemic", "reliability"))

_ax("AX45", "Preserved Reception",
    "Sünuhat resists revision. Roughness = signal, not noise.",
    "C-071", 3, ("epistemic", "methodology"))

_ax("AX46", "Three Paths",
    "Enfüsî (inner) | Afakî (outer) | Berzahî (integrating)",
    "C-072", 3, ("epistemic", "paths"))

_ax("AX47", "Cadde-i Kübra",
    "Properties: safe, universal, fast; Scope: total; Position: center",
    "C-073", 3, ("epistemic", "paths"))

_ax("AX48", "Knowledge Target",
    "Target = İlmelyakîn(grade) at Hakkalyakîn(intensity); Method = Burhani ∧ Kur'anî",
    "C-074", 3, ("epistemic", "target"))

_ax("AX49", "Latifeler Architecture",
    "Latifeler = {Akıl, Kalb, Ruh, Sır, Hafî, Ahfâ} (+ Nefs); Berzahî requires ALL",
    "C-075", 3, ("epistemic", "faculty"))

_ax("AX50", "Elvan-ı Seb'a (Seven Colors)",
    "WhiteLight(Kur'an) = ⊕₁⁷ Color_i; Convergence = resynthesize",
    "C-077", 3, ("epistemic", "faculty"))

# ── Layer 5 — Instrument Specifications ─────────────────────────

_ax("AX51", "Quality Framework",
    "Every instrument output evaluated by Quality Framework; 4 components: Q-1..Q-4",
    "C-082", 5, ("quality", "framework"))

_ax("AX52", "Multiplicative Gate",
    "Gate(A) = ∏ᵢ 𝟙(bᵢ > 0); zero in ANY dimension = collapse",
    "C-083", 5, ("quality", "coverage"))

_ax("AX53", "Ahfâ Inaccessibility",
    "□(φ_L(Ahfâ) = ⊥) — Ahfâ is permanently unmapped",
    "C-084", 5, ("quality", "coverage", "critical"))

_ax("AX54", "Axis Independence",
    "Latife coverage and Medium coverage are independent axes",
    "C-086", 5, ("quality", "coverage"))

_ax("AX55", "Dual Coverage Gate",
    "PracticalGate = Gate(latife₆) ∧ Gate(medium₃)",
    "C-086", 5, ("quality", "coverage"))

_ax("AX56", "Hakkalyakîn Inaccessibility",
    "□(grade⁻¹(H) = ∅) — no instrument reaches Hakkalyakîn",
    "C-087", 5, ("quality", "epistemic", "critical"))

_ax("AX57", "Transparency Requirement",
    "Every output MUST include transparency statement: latife_vektor, ortam_vektor, grade, kavaid",
    "C-095", 5, ("quality", "transparency", "mandatory"))

# ── Appendix A — Nuances (AX58–AX63) ───────────────────────────

_ax("AX58", "Şuhud–İstidlal Gap",
    "Formalization ≤ İstidlal, never = Şuhud; Maps structure, not existential effect",
    "N-1", 7, ("nuance", "critical"))

_ax("AX59", "Celâl Inclusion",
    "BesmeleSeed = Cemâlî(B01..B20) ∪ Celâlî(B21, B22)",
    "N-2", 7, ("nuance", "holographic"))

_ax("AX60", "Evil as Morphism-Absence",
    "Evil = absence of morphism, not a morphism itself",
    "N-3", 7, ("nuance", "privation"))

_ax("AX61", "Acz/Fakr Dual Nature",
    "Structure = constant; Valence = f(ImanLevel) — transformable",
    "N-4", 7, ("nuance", "dependency"))

_ax("AX62", "Nefs Station Ascent",
    "Emmare → Levvame → Mulhime → Mutmainne; Payoff transforms with station",
    "N-5", 7, ("nuance", "station"))

_ax("AX63", "Âyetü'l-Kübrâ Convergence",
    "Affirmations compose super-additively (tesanüd); Denials remain isolated (infirâdî)",
    "N-6", 7, ("nuance", "convergence"))

# ── Layer 6 — Structural Integrity ──────────────────────────────

_ax("AX64", "Source Text Immutability",
    "∀source ∈ SourceTexts: Immutable(source); No tahrifat permitted",
    "C-110", 6, ("integrity", "critical"))

_ax("AX65", "Reference Pairing",
    "∀formalization: ∃ref(formalization) → OriginalText",
    "C-110", 6, ("integrity",))

_ax("AX66", "Ada-First Strategy",
    "Each unit analyzed independently; bridging only after all units complete",
    "C-112", 6, ("integrity", "methodology"))


# ---------------------------------------------------------------------------
# THEOREM REGISTRY — All 15 defined theorems
# ---------------------------------------------------------------------------

_THEOREM_REGISTRY: dict[str, Theorem] = {}


def _thm(id: str, name: str, statement: str, source_ref: str,
         layer: int, depends_on: tuple[str, ...] = ()) -> None:
    """Register a theorem in the internal registry."""
    _THEOREM_REGISTRY[id] = Theorem(
        id=id, name=name, formula=None,
        statement=statement, source_ref=source_ref,
        layer=layer, depends_on=depends_on,
    )


_thm("T3", "Kemal Propagation",
     "∀i ∈ {1..5}: Kemal(Layer_i) = ∞ → Kemal(Layer_{i+1}) = ∞",
     "§2.2", 2, ("AX14",))

_thm("T4", "Name Coherence",
     "¬Conflict(n₁, n₂) because same Zât; Divergence → Miscalibrated lens",
     "§2.4", 2, ("AX17",))

_thm("T5", "Spectrum Continuity",
     "Name-degree spaces are dense continua",
     "§2.6", 2, ("AX21",))

_thm("T6", "Convergence Bound",
     "AccessibleDegree < sup → ConvergenceScore < 1.000",
     "§2.6", 2, ("AX21", "AX22"))

_thm("T7", "Creation Motor",
     "All creation exists because Beauty desires mirrors",
     "§2.7", 2, ("AX24", "AX25"))

_thm("T8", "Cascade Neighborliness",
     "kaskad(n₁,n₂) → (Detectable(n₁) → PredictablyDetectable(n₂))",
     "§2.7", 2, ("AX23",))

_thm("T9", "Multi-Name Necessity",
     "Mediation enables multi-channel expression → causes must exist",
     "§2.8", 2, ("AX26", "AX27"))

_thm("T10", "Severed Cause Impossibility",
     "Sever(cause, context) → ¬CanFunction(cause)",
     "§2.8", 2, ("AX27",))

_thm("T12", "Besmele Seed",
     "Structure(Besmele) ≅ Structure(Fatiha) ≅ Structure(Kur'an)",
     "§2.11", 2, ("AX37",))

_thm("T13", "İnsan = Besmele of Cosmos",
     "Structure(İnsan) ≅ Structure(Besmele(Kâinat))",
     "§2.11", 2, ("AX37",))

_thm("T14", "Universal Ne Ayn Ne Gayr Chain",
     "∀(i, i+1): 0 < Fidelity(i, i+1) < 1",
     "§2.11", 2, ("AX37", "AX38"))

_thm("T15", "Convergence Gradient",
     "Convergence(structural_level) > Convergence(detail_level)",
     "§3.2", 3, ("AX44",))

_thm("T16", "Single-Faculty Limitation",
     "Single-faculty emphasis → velayet in that domain, child-level elsewhere",
     "§3.4", 3, ("AX49",))

_thm("T17", "Structural Completeness Bound",
     "max(|{l | latife_vektor(t)[l] = 1}|) = 6; Coverage ≤ 6/7",
     "§5.2", 5, ("AX49", "AX53"))

_thm("T18", "Per-Module Diagnostic",
     "Each module generates: b ∈ {0,1}⁷ completeness vector, max = 6",
     "§5.5", 5, ("AX57",))


# ---------------------------------------------------------------------------
# KAVAID REGISTRY — All 8 kavaid
# ---------------------------------------------------------------------------

_KAVAID_REGISTRY: dict[str, Kavaid] = {}


def _kv(id: str, name: str, constraint: str, source_ref: str,
        is_critical: bool = False) -> None:
    """Register a kavaid in the internal registry."""
    _KAVAID_REGISTRY[id] = Kavaid(
        id=id, name=name,
        constraint=constraint, source_ref=source_ref,
        is_critical=is_critical,
    )


_kv("KV1", "Mana-yı Harfî / İsmî Dual Classification",
    "∀c ∈ KAVRAMLAR: DualClass(c) ∈ {harfî, ismî}",
    "C-089")

_kv("KV2", "Privation Ontology of Evil",
    "Evil(c) → OntologicalType(c) = adem; ¬∃c: Evil(c) ∧ Vucud(c)",
    "C-090")

_kv("KV3", "Observer = Şart-ı Âdî",
    "Methodology detects, never creates order; Perturbation invariance",
    "C-091")

_kv("KV4", "Ne Ayn Ne Gayr Convergence Bound",
    "0 < Composite < 1; If Composite ≥ 0.95 → ERROR",
    "C-092", is_critical=True)

_kv("KV5", "Temsil → Hakikat Functor Verification",
    "F must be faithful + natural (structure-preserving morphism)",
    "C-093")

_kv("KV6", "Holographic Seed Omnipresence",
    "∀module: HolographicConstant(module) > 0",
    "C-093")

_kv("KV7", "İhlâs (Independence)",
    "∀m₁, m₂ ∈ S_Mercek: m₁ ≠ m₂ → ¬SharedState(m₁, m₂)",
    "C-093", is_critical=True)

_kv("KV8", "Hakikat-i Eşya = Esmâ",
    "∀c ∈ KAVRAMLAR: |esma_mapping(c)| ≥ 1; OntologicalMode = harfî",
    "C-094")


# ---------------------------------------------------------------------------
# INFERENCE CHAINS (AGENTS.md IG.2) — 7 primary chains
# ---------------------------------------------------------------------------

INFERENCE_CHAINS: dict[str, dict] = {
    "C1": {
        "name": "Ontological Poverty → Provision",
        "nodes": ["AX30", "AX31", "AX32", "AX33", "AX34", "AX61"],
        "description": "Structural gaps are functional interfaces",
    },
    "C2": {
        "name": "Beauty → Creation",
        "nodes": ["AX24", "AX25", "T7", "AX23", "T8"],
        "description": "Beauty desires mirrors → cascade structure",
    },
    "C3": {
        "name": "Holographic → Participation → Convergence Bound",
        "nodes": ["AX37", "AX38", "T12", "T13", "T14", "T6", "KV4"],
        "description": "Holographic structure entails bounded fidelity",
    },
    "C4": {
        "name": "Faculties → Coverage → Structural Incompleteness",
        "nodes": ["AX49", "AX50", "AX53", "T17", "AX56", "AX58", "KV4"],
        "description": "Faculty architecture determines formal reach",
    },
    "C5": {
        "name": "Station Hierarchy → Formalization Limits",
        "nodes": ["AX40", "AX41", "AX42", "AX43", "AX39", "AX58"],
        "description": "Epistemic hierarchy calibrates project station",
    },
    "C6": {
        "name": "Names → Dual Meaning → Harfî Mode",
        "nodes": ["AX17", "KV1", "KV8"],
        "description": "Names constitute reality, default harfî mode",
    },
    "C7": {
        "name": "Continuous Degrees → Unreachable Supremum → Score Bound",
        "nodes": ["AX21", "AX22", "T5", "T6", "KV4"],
        "description": "Convergence scores bounded below 1.0",
    },
}

# Hub nodes — highest in-degree across chains (AGENTS.md IG.3)
HUB_NODES: dict[str, list[str]] = {
    "KV4": ["C3", "C4", "C7"],
    "OR-2": ["C4", "C5"],
    "T6": ["C3", "C7"],
    "AX58": ["C4", "C5"],
}


# ---------------------------------------------------------------------------
# PUBLIC API — Lookup functions
# ---------------------------------------------------------------------------

def get_axiom(axiom_id: str) -> Axiom | None:
    """Retrieve an axiom by ID (e.g. 'AX1', 'AX17').

    Returns None if the ID is in a numbering gap or not found.
    """
    return _AXIOM_REGISTRY.get(axiom_id)


def get_theorem(theorem_id: str) -> Theorem | None:
    """Retrieve a theorem by ID (e.g. 'T3', 'T15').

    Returns None if the ID is in a numbering gap or not found.
    """
    return _THEOREM_REGISTRY.get(theorem_id)


def get_kavaid(kavaid_id: str) -> Kavaid | None:
    """Retrieve a kavaid by ID (e.g. 'KV1', 'KV4').

    Returns None if not found.
    """
    return _KAVAID_REGISTRY.get(kavaid_id)


def axioms_by_layer(layer: int) -> list[Axiom]:
    """Return all axioms belonging to a given AGENTS.md layer (1–7)."""
    return [ax for ax in _AXIOM_REGISTRY.values() if ax.layer == layer]


def axioms_by_tag(tag: str) -> list[Axiom]:
    """Return all axioms that have a given tag."""
    return [ax for ax in _AXIOM_REGISTRY.values() if tag in ax.tags]


def list_all_axioms() -> list[Axiom]:
    """Return all defined axioms in ID order."""
    def sort_key(ax: Axiom) -> int:
        num = ax.id.replace("AX", "")
        try:
            return int(num)
        except ValueError:
            return 999
    return sorted(_AXIOM_REGISTRY.values(), key=sort_key)


def list_all_theorems() -> list[Theorem]:
    """Return all defined theorems in ID order."""
    def sort_key(th: Theorem) -> int:
        num = th.id.replace("T", "")
        try:
            return int(num)
        except ValueError:
            return 999
    return sorted(_THEOREM_REGISTRY.values(), key=sort_key)


def list_all_kavaid() -> list[Kavaid]:
    """Return all 8 kavaid in ID order."""
    def sort_key(kv: Kavaid) -> int:
        num = kv.id.replace("KV", "")
        try:
            return int(num)
        except ValueError:
            return 999
    return sorted(_KAVAID_REGISTRY.values(), key=sort_key)


def defined_axiom_ids() -> set[str]:
    """Return the set of all defined axiom IDs."""
    return set(_AXIOM_REGISTRY.keys())


def gap_axiom_ids() -> set[str]:
    """Return the set of unassigned axiom IDs (numbering gaps per IG.6)."""
    return set(_GAP_AXIOM_IDS)


def gap_theorem_ids() -> set[str]:
    """Return the set of unassigned theorem IDs (numbering gaps per IG.6)."""
    return set(_GAP_THEOREM_IDS)


def theorem_dependencies(theorem_id: str) -> list[str]:
    """Return the dependency list for a given theorem.

    Returns empty list if theorem not found.
    """
    th = get_theorem(theorem_id)
    if th is None:
        return []
    return list(th.depends_on)


def check_dependency_closure(
    theorem_id: str,
    axiom_set: set[str] | None = None,
) -> tuple[bool, list[str]]:
    """Check that all dependencies of a theorem are resolved.

    If *axiom_set* is provided, checks that every dependency of the
    theorem appears in that set.  Otherwise, checks that every
    dependency is a defined axiom or theorem in the global registry.

    Returns (all_resolved, list_of_missing_ids).
    """
    th = get_theorem(theorem_id)
    if th is None:
        return False, [theorem_id]

    missing = []
    for dep_id in th.depends_on:
        if axiom_set is not None:
            if dep_id not in axiom_set:
                missing.append(dep_id)
        else:
            if dep_id not in _AXIOM_REGISTRY and dep_id not in _THEOREM_REGISTRY:
                missing.append(dep_id)

    return len(missing) == 0, missing
