#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Brain monitoring dashboard command."""
from __future__ import annotations

import json
from datetime import datetime, timezone

from pulse.cli import ROOT_DIR, STATE_DIR
from pulse.cli.cmd_costs import show_agent_compliance


def cmd_brain():
    """Brain usage dashboard: queries, file sizes, compliance."""
    print("=" * 60)
    print("  PULSE Brain Dashboard")
    print("=" * 60)

    # Query log stats
    query_log = STATE_DIR / "brain_query_log.json"
    queries_24h = 0
    top_queries: dict[str, int] = {}
    if query_log.exists():
        try:
            import datetime as _dt
            entries = json.loads(query_log.read_text(encoding="utf-8"))
            if isinstance(entries, list):
                cutoff = datetime.now(timezone.utc) - _dt.timedelta(hours=24)
                for e in entries:
                    ts = e.get("timestamp", "")
                    q = e.get("query", "")[:40]
                    if ts:
                        try:
                            entry_time = datetime.fromisoformat(ts.replace("Z", "+00:00"))
                            if entry_time > cutoff:
                                queries_24h += 1
                                top_queries[q] = top_queries.get(q, 0) + 1
                        except (ValueError, TypeError):
                            pass
        except Exception:
            pass

    print("")
    print(f"  Queries (last 24h): {queries_24h}")
    if top_queries:
        print("  Top queries:")
        for q, count in sorted(top_queries.items(), key=lambda x: -x[1])[:5]:
            print(f"    [{count}x] {q}")

    # Brain file sizes
    hippocampus = ROOT_DIR / "Hippocampus"
    print("")
    print(f"  Brain Files:")
    brain_files = [
        ("Lessons", hippocampus / "Lessons" / "auto_lessons.md"),
        ("Failures", hippocampus / "Failures" / "auto_fails.md"),
        ("Patterns", hippocampus / "Patterns" / "auto_patterns.md"),
        ("Evidence", hippocampus / "Evidence"),
        ("Knowledge", hippocampus / "Knowledge"),
        ("Private", hippocampus / "Private"),
    ]
    for label, path in brain_files:
        if path.is_file():
            print(f"    {label:<12} {path.stat().st_size / 1024:.1f} KB")
        elif path.is_dir():
            total = sum(f.stat().st_size for f in path.rglob("*") if f.is_file())
            count = sum(1 for _ in path.rglob("*") if _.is_file())
            print(f"    {label:<12} {total / 1024:.1f} KB ({count} files)")

    show_agent_compliance()
    print("")
    print("=" * 60)
