"""
Poetic Error Message Generator v0.1
A deterministic bureaucracy for summoning ghosts from seeds.
Output is a formatted error docket.
"""
from __future__ import annotations
import hashlib
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone

SUBSYSTEMS = [
    "query_planner",
    "ranking_service",
    "search_index",
    "vector_store",
    "embedding_cache",
    "content_filter",
    "locale_router",
    "auth_gate",
    "telemetry_bus",
    "archival_gateway",
]

FAILURES = [
    "results_too_short",
    "empty_result_set",
    "response_truncated",
    "partial_merge_suppressed",
    "shard_timeout",
    "vector_miss",
    "dedup_overreach",
    "schema_mismatch",
    "consensus_did_not_form",
    "quota_silence",
]

REASONS = [
    "minimum_results_threshold not met after dedup; merge produced <k candidates",
    "latency_budget_ms exceeded; partial results discarded to preserve monotonic relevance",
    "safety/content policy quarantined all candidates; silence returned to maintain invariants",
    "index snapshot lag detected; requested documents not visible in current epoch",
    "embedding drift: similarity scores fell below epsilon across primary shards",
    "locale mismatch: fallback disabled to avoid cross-region semantic leakage",
    "auth context under-scoped; archival gateway refused to reveal older strata",
    "telemetry checksum failed; audit lock engaged until provenance is reconstructed",
    "query interpreted as ambiguous; disambiguation required but interaction budget was 0",
    "protected_band active upstream; measurement deferred; response withheld to prevent harm",
]

SEVERITIES = ["INFO", "WARN", "ERROR", "FATAL"]

@dataclass(frozen=True)
class PoeticError:
    timestamp: str
    severity: str
    code: str
    subsystem: str
    failure: str
    reason: str
    operator_note: str

def _u32(b: bytes) -> int:
    return int.from_bytes(b, "big", signed=False)

def generate(seed: str) -> PoeticError:
    """Deterministically generate a poetic error docket from a seed string."""
    h = hashlib.sha256(seed.encode("utf-8")).digest()

    # Deterministic timestamp derived from hash: offset from a fixed bureaucratic epoch.
    base = datetime(2019, 1, 1, tzinfo=timezone.utc)
    window_seconds = 12 * 365 * 24 * 3600  # ~12 years
    offset = _u32(h[0:4]) % window_seconds
    ts = (base + timedelta(seconds=offset)).isoformat().replace("+00:00", "Z")

    severity = SEVERITIES[h[4] % len(SEVERITIES)]
    code = f"{severity[0]}-{h[5]:02X}{h[6]:02X}{h[7]:02X}"

    subsystem = SUBSYSTEMS[h[8] % len(SUBSYSTEMS)]
    failure = FAILURES[h[9] % len(FAILURES)]
    reason = REASONS[h[10] % len(REASONS)]

    notes = [
        "Operator note: The archive contains your answer. It was withheld for being the wrong length for this century.",
        "Operator note: Silence was returned as the safest approximation of truth under load.",
        "Operator note: The system is not empty. It is conserving what it cannot justify.",
        "Operator note: Your query was accepted. Your world could not supply enough witnesses.",
        "Operator note: Please widen the time range. The past is stored in colder shards.",
        "Operator note: The threshold is not a number. It is a doctrine.",
        "Operator note: The clerk in the wire heard you. The policy did not.",
        "Operator note: Try again when you can tolerate an answer that changes you.",
    ]
    operator_note = notes[h[11] % len(notes)]

    return PoeticError(
        timestamp=ts,
        severity=severity,
        code=code,
        subsystem=subsystem,
        failure=failure,
        reason=reason,
        operator_note=operator_note,
    )

def format_docket(e: PoeticError) -> str:
    """Format the error as a bureaucratic docket."""
    return (
        f"{e.timestamp} [{e.severity} {e.code}] {e.subsystem}: {e.failure} — {e.reason}\n"
        f"{e.operator_note}"
    )

if __name__ == "__main__":
    # Example usage
    import sys
    seed = sys.argv[1] if len(sys.argv) > 1 else "kafka_metamorphosis"
    print(format_docket(generate(seed)))
