"""
Circadian engine data models — state enum and report dataclasses.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import TYPE_CHECKING, List, Optional

if TYPE_CHECKING:
    from cortex.identity.cornerstone import DriftReport


class CircadianState(str, Enum):
    """Session lifecycle states."""
    AWAKE = "awake"
    DROWSY = "drowsy"
    SLEEPING = "sleeping"
    DREAMING = "dreaming"
    WAKING = "waking"
    SHUTDOWN = "shutdown"


# Key used in cortex_config table for persisted shutdown state
_CIRCADIAN_STATE_KEY = "circadian_state"


@dataclass
class WakeReport:
    """Result of a wake() call."""
    session_id: str
    cornerstones_loaded: int
    cornerstone_tokens: int
    context_retrieved: Optional[str]
    orphans_recovered: int
    started_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())


@dataclass
class NapReport:
    """Result of a nap() mini-consolidation."""
    session_id: str
    fatigue_before: float
    fatigue_after: float = 0.4
    claims_flushed: int = 0
    summary: str = ""
    completed_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())


@dataclass
class SleepReport:
    """Result of a sleep() call (full consolidation in M6b; stub here)."""
    session_id: str
    duration_ms: int = 0
    claims_created: int = 0
    claims_promoted: int = 0
    claims_pruned: int = 0
    drift_checks: List["DriftReport"] = field(default_factory=list)
    summary: str = ""
    completed_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())


@dataclass
class DreamReport:
    """Result of a dream() cycle (deep consolidation in M6b; stub here)."""
    owner_id: str
    duration_ms: int = 0
    orphans_recovered: int = 0
    claims_consolidated: int = 0
    contradictions_resolved: int = 0
    claims_decayed: int = 0
    claims_archived: int = 0
    cornerstone_proposals: int = 0
    entity_merge_suggestions: int = 0
    brain_graphs_refreshed: int = 0
    feedback_applied: int = 0
    journal: str = ""
    completed_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())


@dataclass
class ShutdownReport:
    """Result of a shutdown() call."""
    sessions_slept: int = 0
    tasks_cancelled: int = 0
    state_persisted: bool = False
    triggered_by: str = "manual"
    completed_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())


# Fatigue constants
FATIGUE_TIME_INCREMENT = 0.01     # +0.01 per interval
# Default value for backward-compatibility; actual value comes from CortexConfig.fatigue_interval_sec
FATIGUE_TIME_INTERVAL_SEC = 300
FATIGUE_COMPACTION_BUMP = 0.15    # +0.15 per compaction event
FATIGUE_ERROR_BUMP = 0.05         # +0.05 per error/retry
FATIGUE_AFTER_NAP = 0.4           # reset fatigue to this after nap
FATIGUE_MAX = 1.0
