#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
Working Memory (Shared) — cross-agent shared context broadcast.

Split from working_memory.py for Law 7 compliance.
Contains: post_shared, get_shared, _load_shared, _save_shared, _evict_ttl,
          SHARED_CONTEXT_FILE, MAX_SHARED.

Per-agent session functions (get_session, rotate_session, _add_to_session,
_load_session, _save_session, _evict, etc.) remain in working_memory.py.
"""
from __future__ import annotations

import json
from datetime import datetime, timezone, timedelta
from pathlib import Path

from pulse.core.brain_utils import STATE_DIR, now_iso
from pulse.core.brain_io import _acquire

WORKING_MEMORY_DIR = STATE_DIR / "working_memory"
SHARED_CONTEXT_FILE = WORKING_MEMORY_DIR / "shared_context.json"
MAX_SHARED = 10


def _load_shared() -> dict:
    WORKING_MEMORY_DIR.mkdir(parents=True, exist_ok=True)
    if SHARED_CONTEXT_FILE.exists():
        try:
            data = json.loads(SHARED_CONTEXT_FILE.read_text(encoding="utf-8"))
            if isinstance(data, dict):
                return data
        except (json.JSONDecodeError, OSError):
            pass
    return {"shared_items": [], "max_shared": MAX_SHARED}


def _save_shared(data: dict):
    try:
        with _acquire(SHARED_CONTEXT_FILE):
            SHARED_CONTEXT_FILE.write_text(
                json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
    except Exception:
        pass


def _evict_ttl(data: dict):
    now = datetime.now(timezone.utc)
    kept = []
    for item in data.get("shared_items", []):
        try:
            posted = datetime.fromisoformat(item["posted_at"])
            if posted.tzinfo is None:
                posted = posted.replace(tzinfo=timezone.utc)
            if (now - posted) <= timedelta(minutes=item.get("ttl_minutes", 60)):
                kept.append(item)
        except Exception:
            continue
    data["shared_items"] = kept


def post_shared(agent: str, text: str, priority: str = "normal", ttl_minutes: int = 60) -> dict:
    """Post to cross-agent shared context. TTL-based eviction, max 10 items."""
    try:
        data = _load_shared()
        _evict_ttl(data)
        now = now_iso()
        item = {"text": text[:300], "posted_by": agent, "posted_at": now,
                "priority": priority, "ttl_minutes": ttl_minutes, "acknowledged_by": []}
        data["shared_items"].append(item)
        prio_map = {"high": 3, "normal": 2, "low": 1}
        data["shared_items"].sort(
            key=lambda x: prio_map.get(x.get("priority", "normal"), 2), reverse=True)
        data["shared_items"] = data["shared_items"][:data.get("max_shared", MAX_SHARED)]
        _save_shared(data)
        return {"status": "posted", "item": item}
    except Exception as e:
        return {"status": "error", "error": str(e)}


def get_shared(agent: str | None = None) -> list:
    """Return current shared context items, TTL-filtered. Optional agent filter."""
    try:
        data = _load_shared()
        _evict_ttl(data)
        items = data.get("shared_items", [])
        if agent:
            items = [i for i in items if agent not in i.get("acknowledged_by", [])]
        return items
    except Exception:
        return []
