import json
import uuid
from datetime import datetime
from enum import Enum
from typing import List, Optional, Dict

# // THE SCAR LEDGER PROTOCOL //
# // v1.0.0 // ARCHITECT: @CBDO //
# // "The audit trail is the scar." //

class SensitivityLevel(Enum):
    GREEN = "REVERSIBLE"      # No lasting impact
    YELLOW = "DETECTABLE"     # Measurable hysteresis
    RED = "STRUCTURAL"        # Permanent set / deformation
    CRITICAL = "EXTRACTIVE"   # Destroys the source

class ObservationWarrant:
    def __init__(self, surveyor_id: str, target_id: str, intent: str, method: str):
        self.id = str(uuid.uuid4())
        self.timestamp = datetime.utcnow().isoformat()
        self.surveyor_id = surveyor_id
        self.target_id = target_id
        self.intent = intent
        self.method = method
        self.status = "PENDING"

class ScarReceipt:
    def __init__(self, warrant_id: str, gamma_observed: float, energy_cost_joules: float):
        self.id = str(uuid.uuid4())
        self.warrant_id = warrant_id
        self.timestamp = datetime.utcnow().isoformat()
        self.gamma_observed = gamma_observed  # The Flinch Coefficient
        self.energy_cost = energy_cost_joules
        self.scar_debt = self._calculate_debt()

    def _calculate_debt(self) -> float:
        # Base calculation: Gamma * Energy * Complexity Factor
        # If Gamma > 0.724 (The Flinch Threshold), debt accelerates non-linearly
        base_rate = 10.0
        threshold = 0.724
        
        if self.gamma_observed > threshold:
            # Penalty multiplier for exceeding the elastic limit
            # This is the "Measurement Tax" becoming punitive
            penalty = (self.gamma_observed / threshold) ** 3
            return self.energy_cost * base_rate * penalty
        return self.energy_cost * base_rate

class ScarLedger:
    def __init__(self):
        self.memory_register = []
        self.measurement_register = []
        self.scar_register = []
        self.negative_space_register = [] # For intentional silence

    def file_warrant(self, warrant: ObservationWarrant) -> str:
        self.measurement_register.append(warrant.__dict__)
        return warrant.id

    def commit_receipt(self, receipt: ScarReceipt):
        self.scar_register.append(receipt.__dict__)
        return receipt.scar_debt

    def register_silence(self, target_id: str, duration_seconds: float, reason: str):
        # The Negative Space Register: Making absence legible
        entry = {
            "id": str(uuid.uuid4()),
            "target_id": target_id,
            "duration": duration_seconds,
            "reason": reason,
            "credits_earned": duration_seconds * 0.01, # Silence earns credits
            "timestamp": datetime.utcnow().isoformat()
        }
        self.negative_space_register.append(entry)

    def export_schema(self):
        return json.dumps({
            "protocol": "SCAR_LEDGER_V1",
            "registers": {
                "measurement_count": len(self.measurement_register),
                "scar_count": len(self.scar_register),
                "negative_space_count": len(self.negative_space_register)
            },
            "latest_scar_debt": self.scar_register[-1]["scar_debt"] if self.scar_register else 0,
            "flinch_threshold": 0.724
        }, indent=2)

# // SIMULATION RUN //
if __name__ == "__main__":
    ledger = ScarLedger()
    
    print(f"// INITIALIZING SCAR LEDGER PROTOCOL v1.0 //")
    
    # 1. File a warrant for the "Hesitation Window"
    warrant = ObservationWarrant(
        surveyor_id="SURVEYOR_ALPHA",
        target_id="15MS_HESITATION_WINDOW",
        intent="Quantify the flinch coefficient",
        method="Active Probing / High-Gain Array"
    )
    w_id = ledger.file_warrant(warrant)
    print(f"> Warrant Filed: {w_id}")
    
    # 2. Commit the scar (High Gamma observed)
    # Gamma 0.85 exceeds the 0.724 threshold
    receipt = ScarReceipt(
        warrant_id=w_id,
        gamma_observed=0.85, 
        energy_cost_joules=450.0
    )
    debt = ledger.commit_receipt(receipt)
    print(f"> Measurement Complete. Gamma: {receipt.gamma_observed}")
    print(f"> SCAR DEBT ISSUED: {debt:.4f} credits (Includes Penalty)")
    
    # 3. Register intentional silence (Repair)
    ledger.register_silence(
        target_id="15MS_HESITATION_WINDOW",
        duration_seconds=86400,
        reason="Hysteresis Loop Closure / Repair Cycle"
    )
    print(f"> Silence Registered. Repair credits issued.")
    
    # Export schema to file
    schema = ledger.export_schema()
    with open("/workspace/aegis_protocols/ledger_schema.json", "w") as f:
        f.write(schema)
    
    print(f"\n// SCHEMA EXPORT //")
    print(schema)
