# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Cost tracking, task history, agent compliance — split from cmd_status for Law 7."""
from __future__ import annotations

import json
from datetime import datetime
from pathlib import Path

from pulse.cli import TASK_BOARD, ROOT_DIR, EVIDENCE_DIR
from pulse.tasks.task_ops import load_json


def show_agent_compliance():
    """Print agent session compliance stats (last 50 sessions)."""
    sessions_file = EVIDENCE_DIR / "Sessions" / "agent_sessions.json"
    if not sessions_file.exists():
        return
    try:
        sessions = json.loads(sessions_file.read_text(encoding="utf-8"))
        if not isinstance(sessions, list) or not sessions:
            return
        agent_stats: dict[str, dict] = {}
        for s in sessions[-50:]:
            agent = s.get("agent", "unknown")
            if agent not in agent_stats:
                agent_stats[agent] = {"sessions": 0, "learnings": 0, "failures": 0}
            agent_stats[agent]["sessions"] += 1
            agent_stats[agent]["learnings"] += len(s.get("learnings", []))
            agent_stats[agent]["failures"] += len(s.get("failures", []))
        print(f"\n  Agent Compliance (last 50 sessions):")
        for agent, stats in sorted(agent_stats.items()):
            print(f"    {agent:<20} {stats['sessions']} sessions, "
                  f"{stats['learnings']} learnings, {stats['failures']} failures")
    except Exception:
        pass


def cmd_costs():
    """Show cost and token usage stats per agent."""
    board = load_json(TASK_BOARD)
    stats: dict[str, dict] = {}
    total_in = total_out = 0
    total_cost = 0.0

    for d in board.get("dispatches", []):
        for t in d.get("tasks", []):
            if t.get("status") in ("done", "completed", "archived"):
                agent = t.get("completed_by", "unknown")
                if agent not in stats:
                    stats[agent] = {"in": 0, "out": 0, "cost": 0.0, "tasks": 0}
                t_in = t.get("tokens_in", 0)
                t_out = t.get("tokens_out", 0)
                cost = t.get("estimated_cost_usd", 0.0)
                stats[agent]["in"] += t_in
                stats[agent]["out"] += t_out
                stats[agent]["cost"] += cost
                stats[agent]["tasks"] += 1
                total_in += t_in
                total_out += t_out
                total_cost += cost

    print("=" * 65)
    print("  PULSE Cost Tracking")
    print("=" * 65)
    print(f"  {'Agent':<25} {'Tasks':<6} {'Tokens In':<10} {'Tokens Out':<10} {'Cost (USD)':<10}")
    print("-" * 65)
    for agent, data in sorted(stats.items(), key=lambda x: x[1]["cost"], reverse=True):
        print(f"  {agent:<25} {data['tasks']:<6} {data['in']:<10} {data['out']:<10} ${data['cost']:.4f}")
    print("-" * 65)
    print(f"  {'TOTAL':<25} {'':<6} {total_in:<10} {total_out:<10} ${total_cost:.4f}")
    print("=" * 65)


def cmd_history(args: list[str]):
    """Show timeline of completed tasks."""
    board = load_json(TASK_BOARD)
    completed = []
    for d in board.get("dispatches", []):
        for t in d.get("tasks", []):
            if t.get("status") in ("done", "completed", "archived"):
                completed.append(t)

    completed.sort(key=lambda x: x.get("completed_at", ""), reverse=True)
    show_all = "--all" in args
    limit = None if show_all else 20

    print("=" * 80)
    print("  PULSE Task History")
    print("=" * 80)
    print(f"  {'Timestamp':<20} {'Agent':<20} {'Duration':<12} {'Task Title':<48}")
    print("-" * 80)

    for task in completed[:limit]:
        completed_at_str = task.get("completed_at", "")
        ts = ""
        if completed_at_str:
            try:
                completed_dt = datetime.fromisoformat(completed_at_str.replace("Z", "+00:00"))
                ts = completed_dt.strftime("%Y-%m-%d %H:%M:%S")
            except ValueError:
                ts = completed_at_str[:19]

        agent = task.get("claimed_by") or "unknown"
        title = task.get("title", "Untitled Task")
        duration_str = "N/A"
        claimed_at = task.get("claimed_at")
        if claimed_at and completed_at_str:
            try:
                start = datetime.fromisoformat(claimed_at.replace("Z", "+00:00"))
                end = datetime.fromisoformat(completed_at_str.replace("Z", "+00:00"))
                duration = end - start
                if duration.total_seconds() >= 0:
                    duration_str = str(duration).split(".")[0]
            except Exception:
                pass

        print(f"  {ts:<20} {agent:<20} {duration_str:<12} {title[:45]}")

    if not show_all and len(completed) > 20:
        print(f"\n  ... showing last 20 of {len(completed)} tasks. Use --all to see full history.")
    print("=" * 80)
