"""
CorvOS - Bio-Link Mass Synchronization Module v1.0
Sincronizacao de batimentos cardiacos com pulso de 40Hz
Synapse-k | Arkhe(n) | Rio de Janeiro
"""
import numpy as np
from dataclasses import dataclass, field
from typing import List, Dict, Tuple, Optional
from datetime import datetime, timedelta
import asyncio, random

@dataclass
class ResidentBioState:
    resident_id: str
    baseline_hr: float       # bpm
    current_hr: float        # bpm
    hrv: float               # heart rate variability (ms)
    coherence: float         # 0-1 bio Coherence指标
    sync_status: str        # SYNCHRONIZED / DRIFTING / LOST
    last_pulse: datetime

class BioLinkPulseEngine:
    FREQUENCY_HZ = 40.0      # 40Hz regeneration pulse
    COHERENCE_TARGET = 0.85
    SYNC_WINDOW_MS = 50      # toleranca de sincronia

    def __init__(self):
        self.residents: Dict[str, ResidentBioState] = {}
        self.pulse_history: List[datetime] = []
        self.sync_coherence_map: Dict[str, float] = {}
        self.global_coherence: float = 0.0
        self.pulse_count = 0

    def register_resident(self, resident_id: str, baseline_hr: float):
        self.residents[resident_id] = ResidentBioState(
            resident_id=resident_id,
            baseline_hr=baseline_hr,
            current_hr=baseline_hr,
            hrv=40.0,
            coherence=0.0,
            sync_status="DRIFTING",
            last_pulse=datetime.now()
        )

    def compute_phase_alignment(self, hr: float) -> float:
        beat_interval = 60.0 / hr
        phase = (datetime.now().timestamp() % beat_interval) / beat_interval
        return 2 * np.pi * phase

    async def emit_pulse(self) -> Dict:
        self.pulse_count += 1
        now = datetime.now()
        self.pulse_history.append(now)
        if len(self.pulse_history) > 1000:
            self.pulse_history = self.pulse_history[-1000:]
        aligned, drifting, lost = 0, 0, 0
        for rid, state in self.residents.items():
            phase = self.compute_phase_alignment(state.current_hr)
            pulse_phase = 2 * np.pi * (self.pulse_count % (1000 / self.FREQUENCY_HZ)) / (1000 / self.FREQUENCY_HZ)
            phase_diff = abs(phase - pulse_phase)
            if phase_diff < self.SYNC_WINDOW_MS / 1000 * 2 * np.pi:
                state.sync_status = "SYNCHRONIZED"
                state.coherence = min(1.0, state.coherence + 0.05)
                aligned += 1
            elif phase_diff < 0.5:
                state.sync_status = "DRIFTING"
                state.coherence = max(0.0, state.coherence - 0.02)
                drifting += 1
            else:
                state.sync_status = "LOST"
                state.coherence = max(0.0, state.coherence - 0.1)
                lost += 1
            state.current_hr = min(120, max(50, state.current_hr + random.uniform(-0.5, 0.5)))
        total = len(self.residents) or 1
        self.global_coherence = aligned / total
        return {
            'pulse_count': self.pulse_count,
            'frequency_hz': self.FREQUENCY_HZ,
            'aligned': aligned,
            'drifting': drifting,
            'lost': lost,
            'global_coherence': self.global_coherence,
            'timestamp': now.isoformat()
        }

    def get_sync_report(self) -> Dict:
        if not self.residents:
            return {'total_residents': 0, 'global_coherence': 0.0}
        by_status = {"SYNCHRONIZED": 0, "DRIFTING": 0, "LOST": 0}
        coherences = []
        for s in self.residents.values():
            by_status[s.sync_status] = by_status.get(s.sync_status, 0) + 1
            coherences.append(s.coherence)
        return {
            'total_residents': len(self.residents),
            'by_sync_status': by_status,
            'global_coherence': float(np.mean(coherences)) if coherences else 0.0,
            'pulses_emitted': self.pulse_count,
            'target_frequency_hz': self.FREQUENCY_HZ
        }
