#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Session logging, skill tracking, query counting, and save card output."""
import json
import logging
from datetime import datetime, timezone, timedelta
from pathlib import Path

from pulse.core.brain_utils import atomic_update_json, HIPPOCAMPUS_DIR, now_iso as _now_iso

SCRIPT_DIR = Path(__file__).resolve().parent.parent.parent  # pulse/brain/save_writers -> pulse/brain -> pulse
ROOT_DIR = SCRIPT_DIR.parent  # pulse -> repo root
SESSIONS_FILE = HIPPOCAMPUS_DIR / "Evidence" / "Sessions" / "agent_sessions.json"


def log_session(agent_name: str, task_id: str, learnings: list,
                failures: list, files_touched: list) -> None:
    """Log session to agent_sessions.json for historical tracking."""
    SESSIONS_FILE.parent.mkdir(parents=True, exist_ok=True)

    session = {
        "agent": agent_name,
        "task_id": task_id,
        "learnings": learnings,
        "failures": failures,
        "files_touched": files_touched,
        "timestamp": _now_iso(),
    }
    from pulse.core.pulse_crypto import sign_item
    session = sign_item(session, agent_name)

    def _updater(data):
        if not isinstance(data, list):
            data = []
        data.append(session)
        return data

    # P47: Also write to SQLite sessions table for cross-session persistence
    try:
        from pulse.brain.session.session_lifecycle import end_session, get_active_session
        sid = get_active_session(agent_name)
        if sid:
            end_session(sid, summary=(learnings[0] if learnings else ''),
                       key_discoveries=learnings[:5], files_touched=files_touched[:10])
    except Exception:
        pass
    atomic_update_json(SESSIONS_FILE, _updater, default=[])


def count_brain_queries(agent_name: str = "") -> int:
    """Count brain queries from this session (last 1 hour)."""
    log_file = ROOT_DIR / "state" / "brain_query_log.json"
    if not log_file.exists():
        return 0
    try:
        entries = json.loads(log_file.read_text(encoding="utf-8"))
        if not isinstance(entries, list):
            return 0
        cutoff = datetime.now(timezone.utc) - timedelta(hours=1)
        count = 0
        for e in entries:
            ts = e.get("timestamp", "")
            if ts:
                try:
                    entry_time = datetime.fromisoformat(ts.replace("Z", "+00:00"))
                    if entry_time > cutoff:
                        count += 1
                except (ValueError, TypeError):
                    logging.debug("Suppressed exception in save_writers/session", exc_info=True)
        return count
    except Exception:
        return 0


def record_skill_usage(skills_used: list, had_failures: bool) -> int:
    """Record skill usage for effectiveness tracking."""
    if not skills_used:
        return 0
    try:
        from pulse.admin.skills.skill_effectiveness import record_usage
        count = 0
        for skill in skills_used:
            skill = skill.strip()
            if skill:
                record_usage(skill, success=not had_failures)
                count += 1
        return count
    except ImportError:
        return 0


def record_procedure(procedure_id: str, had_failures: bool) -> dict:
    """Record a procedure execution via procedural_tracker."""
    if not procedure_id:
        return {}
    try:
        from pulse.admin.procedural_tracker import record_execution
        return record_execution(procedure_id, success=not had_failures)
    except ImportError:
        return {}


def build_save_card(agent_name: str, results: dict) -> str:
    """Build confirmation card for save results."""
    lines = ["", "+" + "=" * 50 + "+",
             "|  PULSE SWARM \u2014 Session Saved" + " " * 21 + "|",
             "+" + "=" * 50 + "+"]
    lines.append(f"|  Agent:       {agent_name:<36}|")
    lines.append(f"|  Task Done:   {'YES' if results['task_marked_done'] else 'N/A':<36}|")
    lines.append(f"|  Learnings:   {results['learnings_saved']:<36}|")
    lines.append(f"|  Failures:    {results['failures_saved']:<36}|")
    lines.append(f"|  Session Log: {'YES' if results['session_logged'] else 'NO':<36}|")
    lines.append(f"|  Registry:    {'Updated' if results['registry_updated'] else 'Failed':<36}|")
    bq = results.get("brain_queries", 0)
    brain_str = f"YES ({bq} queries)" if bq > 0 else "NO \u2014 VIOLATION"
    lines.append(f"|  Brain Used:  {brain_str:<36}|")
    lines.extend(["+" + "=" * 50 + "+",
                   "|  Brain updated. Next agent will see your work.  |",
                   "+" + "=" * 50 + "+", ""])
    return "\n".join(lines)
