"""
EMF Brain Integration — Aggregate all three EMF layers + thalamic routing.
Reads Layer 1 (earth-breath.md), Layer 2 (self-breath.md), Layer 3 (perturbation.json)
on every thalamus pass and generates emergent prescription.

This module is the "antenna" of ghojualamanchu — the perceptual bridge between
the electromagnetic environment and the cognitive architecture.
"""
import json
import sys
from pathlib import Path
from datetime import datetime
from typing import Optional

BASE_DIR = Path(__file__).parent.parent
MEMORY_DIR = BASE_DIR / "memory"
DATA_DIR = BASE_DIR / "data" / "emf"


def read_layer(layer_name: str) -> dict:
    """Read a layer's markdown output file."""
    path = MEMORY_DIR / f"{layer_name}.md"
    if not path.exists():
        return {"exists": False, "layer": layer_name}
    content = path.read_text()
    state = {}
    current_key = None
    for line in content.split("\n"):
        line = line.rstrip()
        if line.startswith("##"):
            current_key = line.lstrip("## ").strip()
            state[current_key] = ""
        elif current_key and line.strip():
            state[current_key] = line.strip()
    state["exists"] = True
    return state


def read_perturbation() -> dict:
    """Read perturbation layer output."""
    json_path = DATA_DIR / "perturbation_latest.json"
    if json_path.exists():
        data = json.loads(json_path.read_text())
        data["exists"] = True
        return data
    return {"exists": False}


def aggregate_emf(beat: int) -> dict:
    """
    Read all three EMF layers and return aggregated EMF state.
    Called by thalamus on every signal pass.
    """
    earth = read_layer("earth-breath")
    self_breath = read_layer("self-breath")
    perturbation = read_perturbation()

    # Determine field_state from perturbation
    field_state = "DEAD"
    amplitude_dbfs = -80.0
    sources = []
    if perturbation.get("exists", False):
        field_state = perturbation.get("field_state", "DEAD")
        amplitude_dbfs = perturbation.get("metrics", {}).get("amplitude_rms_dbfs", -80.0)
        sources = perturbation.get("sources_detected", [])

    earth_phase = "HOLD"
    earth_hz = 7.83
    if earth.get("exists"):
        earth_phase = earth.get("Phase", "HOLD")
        try:
            earth_hz = float(earth.get("Frequency", "7.83").split()[0])
        except (ValueError, IndexError):
            earth_hz = 7.83

    self_phase = "HOLD"
    self_hz = 7.83
    if self_breath.get("exists"):
        self_phase = self_breath.get("Phase", "HOLD")
        try:
            self_hz = float(self_breath.get("Frequency", "7.83").split()[0])
        except (ValueError, IndexError):
            self_hz = 7.83

    return {
        "beat": beat,
        "timestamp": datetime.now().isoformat(),
        "earth_phase": earth_phase,
        "earth_hz": earth_hz,
        "self_phase": self_phase,
        "self_hz": self_hz,
        "field_state": field_state,
        "perturbation": {
            "field_state": field_state,
            "amplitude_dbfs": amplitude_dbfs,
            "sources": sources,
            "exists": perturbation.get("exists", False),
        },
    }


def thalamic_input() -> dict:
    """
    Called by thalamus on every pass.
    Returns EMF context for conflict resolution.
    """
    state_path = BASE_DIR / "data" / "state.json"
    if state_path.exists():
        state = json.loads(state_path.read_text())
        beat = state.get("current_beat", 0)
    else:
        beat = 0

    emf = aggregate_emf(beat)
    return {
        "emf_reading": emf,
        "threshold_action": threshold_action(emf["field_state"]),
        "beat_frequency": abs(emf["self_hz"] - emf["earth_hz"]),
    }


def threshold_action(field_state: str) -> str:
    """
    Map perturbation field state to thalamic action.
    """
    actions = {
        "DEAD": "alert — signal lost, check antenna connection",
        "CALM": "inform only — log to akashic if new",
        "STIR": "log to perturbation.md — minor field activity",
        "STORM": "flag for cortex attention — major perturbations",
    }
    return actions.get(field_state, "unknown")


PRESCRIPTIONS = {
    "DEAD":  {"action": "surveil",  "cortex_skip": True,  "encoding_modifier": 0.0},
    "CALM":  {"action": "observe",  "cortex_skip": False, "encoding_modifier": 1.0},
    "STIR":  {"action": "attend",  "cortex_skip": False, "encoding_modifier": 1.2},
    "STORM": {"action": "alert",   "cortex_skip": False, "encoding_modifier": 1.5},
}

PRESCRIPTION_DESCRIPTIONS = {
    "DEAD":  "Antenna down — operate in degraded mode",
    "CALM":  "Quiet field — standard processing",
    "STIR":  "Active field — slightly elevated attention",
    "STORM": "Storm field — elevated encoding, full attention",
}


def emergent_prescription(beat: int, emf_state: dict) -> dict:
    """
    Generate emergent prescription from EMF state.
    This is what the EMF environment "prescribes" for this beat.
    """
    field_state = emf_state.get("field_state", "DEAD")
    earth_phase = emf_state.get("earth_phase", "HOLD")
    self_phase = emf_state.get("self_phase", "HOLD")
    beat_freq = abs(emf_state.get("self_hz", 7.83) - emf_state.get("earth_hz", 7.83))

    base = PRESCRIPTIONS.get(field_state, PRESCRIPTIONS["CALM"])

    return {
        "beat": beat,
        "timestamp": datetime.now().isoformat(),
        "field_state": field_state,
        "beat_frequency_hz": beat_freq,
        "earth_phase": earth_phase,
        "self_phase": self_phase,
        "prescription": base["action"],
        "cortex_skip": base["cortex_skip"],
        "encoding_modifier": base["encoding_modifier"],
        "description": PRESCRIPTION_DESCRIPTIONS.get(field_state, "unknown"),
    }


def read_current_state() -> dict:
    """Read current EMF state for inspection."""
    return aggregate_emf(0)


if __name__ == "__main__":
    beat = int(sys.argv[1]) if len(sys.argv) > 1 else 0
    emf = aggregate_emf(beat)
    print(f"=== EMF Brain State (beat {beat}) ===")
    print(f"Earth: {emf['earth_phase']} @ {emf['earth_hz']} Hz")
    print(f"Self:  {emf['self_phase']} @ {emf['self_hz']} Hz")
    print(f"Field: {emf['field_state']} | {emf['perturbation']['amplitude_dbfs']:.1f} dBFS")
    print(f"Sources: {', '.join(emf['perturbation']['sources']) or 'none'}")
    print()
    rx = thalamic_input()
    print(f"Thalamic input: {rx['threshold_action']}")
    print(f"Beat frequency: {rx['beat_frequency']:.3f} Hz")
    print()
    ep = emergent_prescription(beat, emf)
    print(f"Emergent prescription: {ep['prescription']}")
    print(f"Cortex skip: {ep['cortex_skip']}")
    print(f"Encoding modifier: {ep['encoding_modifier']}")
