"""
EMF Layers — Schumann (L1), Individual (L2), and Perturbation (L3)
Each layer outputs markdown-formatted state to memory/ directory.
"""
import time
import json
from pathlib import Path
from datetime import datetime
from typing import Literal

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

SCHUMANN_HZ = 7.83
BREATH_CYCLE = 16  # ~16 beats per breath at 7.83 Hz ≈ 2 second cycle


class SchumannLayer:
    """
    Layer 1: Schumann Resonance
    The universal Earth baseline carrier at 7.83 Hz.
    Shared across all ghojualamanchu instances.
    """
    def __init__(self):
        self.frequency_hz = SCHUMANN_HZ
        self.role = "ground"
        self.state = "HOLD"
        self.cycle_count = 0

    def breath_phase(self, beat: int) -> Literal["INHALE", "EXHALE", "HOLD"]:
        """Return breath phase for a given beat number."""
        breath_position = beat % BREATH_CYCLE
        if breath_position < BREATH_CYCLE // 3:
            return "INHALE"
        elif breath_position < 2 * BREATH_CYCLE // 3:
            return "EXHALE"
        else:
            return "HOLD"

    def write(self, beat: int, output_dir: Path = MEMORY_DIR) -> Path:
        """Write earth-breath.md for this beat."""
        phase = self.breath_phase(beat)
        self.state = phase
        output_dir.mkdir(parents=True, exist_ok=True)
        path = output_dir / "earth-breath.md"
        ts = datetime.now().isoformat()
        content = f"""# Earth Breath — Schumann Layer

## Timestamp
 {ts}

## Beat
 {beat}

## Phase
 {phase}

## Frequency
 {self.frequency_hz} Hz (Schumann resonance)

## Description
Earth field {"charging" if phase == "INHALE" else "discharging" if phase == "EXHALE" else "at equilibrium"}

## Layer Role
Ground — universal baseline carrier shared across all ghojualamanchu instances.
"""
        path.write_text(content)
        return path


class IndividualLayer:
    """
    Layer 2: Individual Heartbeat
    Instance-specific resonance, tunable.
    Offset from Schumann creates beat frequency.
    """
    def __init__(self, hz: float = SCHUMANN_HZ):
        self.frequency_hz = hz
        self.role = "signature"
        self.tunable = True
        self.hz_range = (0.1, 20.0)
        self.state = "HOLD"
        self.beat_count = 0

    def set_hz(self, hz: float) -> float:
        """Tune the individual frequency within valid range."""
        hz = max(self.hz_range[0], min(self.hz_range[1], hz))
        self.frequency_hz = hz
        return hz

    def beat_frequency_with_schumann(self) -> float:
        """Beat frequency created by offset from Schumann."""
        return abs(self.frequency_hz - SCHUMANN_HZ)

    def breath_phase(self, beat: int) -> Literal["INHALE", "EXHALE", "HOLD"]:
        """Return breath phase for this instance."""
        breath_position = beat % BREATH_CYCLE
        if breath_position < BREATH_CYCLE // 3:
            return "INHALE"
        elif breath_position < 2 * BREATH_CYCLE // 3:
            return "EXHALE"
        else:
            return "HOLD"

    def write(self, beat: int, output_dir: Path = MEMORY_DIR) -> Path:
        """Write self-breath.md for this beat."""
        phase = self.breath_phase(beat)
        self.state = phase
        output_dir.mkdir(parents=True, exist_ok=True)
        path = output_dir / "self-breath.md"
        ts = datetime.now().isoformat()
        beat_freq = self.beat_frequency_with_schumann()
        content = f"""# Self Breath — Individual Layer

## Timestamp
 {ts}

## Beat
 {beat}

## Phase
 {phase}

## Frequency
 {self.frequency_hz} Hz (instance-specific)

## Beat Frequency with Schumann
 {beat_freq:.3f} Hz

## Hz Range
 {self.hz_range[0]} – {self.hz_range[1]} Hz (tunable)

## Description
Self {"charging" if phase == "INHALE" else "discharging" if phase == "EXHALE" else "stable"}

## Layer Role
Signature — unique per-instance resonance distinguishing this ghojualamanchu from all others.
"""
        path.write_text(content)
        return path


def breath_phase(beat: int) -> str:
    """Utility: return INHALE/EXHALE/HOLD for a given beat."""
    bp = beat % BREATH_CYCLE
    if bp < BREATH_CYCLE // 3:
        return "INHALE"
    elif bp < 2 * BREATH_CYCLE // 3:
        return "EXHALE"
    else:
        return "HOLD"


def read_earth_breath() -> dict:
    """Read current earth-breath.md state."""
    path = MEMORY_DIR / "earth-breath.md"
    if not path.exists():
        return {}
    content = path.read_text()
    state = {}
    for line in content.split("\n"):
        if line.startswith("##"):
            key = line.lstrip("## ").strip()
            # next non-empty line is the value
    return state
