"""
MODULE 6b: SLEEP CONSOLIDATOR — Memory Scoring, Promotion & Demotion During Sleep
==================================================================================
Implements the full consolidation logic that runs during sleep() and dream() phases.

sleep() pipeline (end-of-session, target <3 min):
  1. SESSION MEMORY DUMP    — flush working memory, generate summary, tag session claims
  2. DEPRECATION REVIEW     — run DeprecationPipeline on session claims
  3. CORNERSTONE DRIFT CHECK — run DriftCalculator on all cornerstones, restore if drifted
  4. QUICK CONSOLIDATION    — fold promoted claims into semantic layer, update edges
  5. SLEEP CONFIRMATION     — log session_record stats, set status='sleeping'

dream() pipeline (nightly, target <10 min):
  1. ORPHAN RECOVERY        — delegate to M6a scheduler for detection, run sleep() on orphans
  2. DEEP CONSOLIDATION     — review all session memories from past 24h
  3. CORNERSTONE EVOLUTION  — propose new cornerstones based on patterns
  4. RECONSOLIDATION        — detect and resolve contradictions in semantic memory
  5. MEMORY DECAY           — reduce confidence on non-accessed claims, archive below threshold
  6. ENTITY MERGE SUGGESTIONS — call entity_resolver.suggest_merges()
  7. BRAIN GRAPH REFRESH    — check source hashes, flag stale graphs
  8. APPLY PENDING FEEDBACK — process memory_feedback with status='pending'
  9. DREAM JOURNAL          — generate DreamReport

Design principles:
  - All public methods are async
  - Hard dependencies injected (no global state)
  - Operations are logged to respective log tables via StorageAdapter
  - Integration hooks: DeprecationPipeline, DriftCalculator, CornerstoneGuardian, EntityResolver
  - Soft-optional: entity_resolver and feedback_system may be None (graceful degradation)
"""

from __future__ import annotations

import json
import logging
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone, timedelta
from typing import TYPE_CHECKING, List, Optional

if TYPE_CHECKING:
    from cortex.storage.adapter import StorageAdapter
    from cortex.config import CortexConfig
    from cortex.types import LLMProvider, SemanticClaim, MergeSuggestion
    from cortex.identity.cornerstone import CornerstoneGuardian
    from cortex.identity.drift_calculator import DriftCalculator, DriftReport
    from cortex.deprecation.pipeline import DeprecationPipeline
    from cortex.core.entity_resolution import EntityResolver
    from cortex.core.feedback import FeedbackSystem

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
# Report dataclasses (M6b additions — matches CircadianEngine stubs from M6a)
# ---------------------------------------------------------------------------

@dataclass
class SleepReport:
    """Full sleep consolidation report."""
    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:
    """Full dream cycle report."""
    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
    peers_refreshed: int = 0
    peer_changes: List[dict] = field(default_factory=list)
    step_results: List[dict] = field(default_factory=list)
    journal: str = ""
    completed_at: str = field(
        default_factory=lambda: datetime.now(timezone.utc).isoformat()
    )


# ---------------------------------------------------------------------------
# LLM prompts
# ---------------------------------------------------------------------------

_SESSION_SUMMARY_SYSTEM = """\
You are a memory consolidation assistant. Your job is to produce a concise,
factual summary of what was learned or discussed in this conversation session.
Focus on durable facts, decisions, and preferences — not transient details.
Respond with plain text, 2-5 sentences maximum."""

_SESSION_SUMMARY_USER = """\
Here are the session memories (claims) to summarize:

{claims_json}

Produce a brief summary of the session's key takeaways."""

_CONTRADICTION_SYSTEM = """\
You are a memory reconsolidation assistant. Given a list of semantic memory claims
for the same subject, identify any direct contradictions. A contradiction is when
two claims make mutually exclusive assertions about the same subject.

Respond with JSON:
{
  "contradictions": [
    {
      "claim_a_id": "<id>",
      "claim_b_id": "<id>",
      "reason": "<brief explanation>",
      "resolution": "supersede_a" | "supersede_b" | "flag_both"
    }
  ]
}
If no contradictions, return {"contradictions": []}."""

_CONTRADICTION_USER = """\
Claims for subject '{subject}':
{claims_json}

Identify contradictions (if any)."""

_CORNERSTONE_PROPOSAL_SYSTEM = """\
You are an identity analyst for an AI agent. Based on recurring themes and
high-confidence patterns from recent conversation sessions, suggest potential
new cornerstone memories — core identity-defining facts that should persist
permanently.

Respond with JSON array:
[{"label": "<short label>", "content": "<cornerstone text>", "reason": "<why important>"}]

Only suggest genuinely identity-defining facts. If nothing qualifies, return [].
Limit to 3 proposals maximum."""

_CORNERSTONE_PROPOSAL_USER = """\
Recent high-confidence claims (past 24h):
{claims_json}

Existing cornerstones (do NOT re-propose these):
{cornerstones_json}

Propose new cornerstone memories (if any)."""


# ---------------------------------------------------------------------------
# SleepConsolidator
# ---------------------------------------------------------------------------


# ---------------------------------------------------------------------------
# SleepConsolidator — extracted to sleep_consolidator.py
# ---------------------------------------------------------------------------

from cortex.circadian.sleep_consolidator import (  # noqa: F401
    SleepConsolidator,
    _parse_dt,
    _parse_json_dict,
    _parse_json_list,
)
