#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
Skill Effectiveness Tracker: Measure which skills agents actually use.

Reads skill usage data from State/skill_usage.json (populated by pulse_save)
and generates effectiveness reports showing usage counts and success rates.

Usage:
    python skill_effectiveness.py                # Full report
    python skill_effectiveness.py --top 10       # Top N skills
    python skill_effectiveness.py --unused        # Skills never used
    python skill_effectiveness.py --json          # JSON output

Dependencies: Python stdlib only (Law 4)
"""

import json
import sys
from pathlib import Path

from pulse.core.brain_io import _acquire

SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent
STATE_DIR = ROOT_DIR / "state"
USAGE_FILE = STATE_DIR / "skill_usage.json"
SKILLS_DIR = ROOT_DIR / ".cursor" / "skills"


def _load_usage() -> dict:
    """Load skill usage data."""
    if not USAGE_FILE.exists():
        return {}
    try:
        data = json.loads(USAGE_FILE.read_text(encoding="utf-8"))
        return data if isinstance(data, dict) else {}
    except (json.JSONDecodeError, Exception):
        return {}


def _list_all_skills() -> list[str]:
    """List all available skill names."""
    skills = []
    if not SKILLS_DIR.exists():
        return skills
    for category in sorted(SKILLS_DIR.iterdir()):
        if not category.is_dir():
            continue
        for skill_file in sorted(category.glob("*.md")):
            skills.append(skill_file.stem)
    return skills


def record_usage(skill_name: str, success: bool = True) -> None:
    """Record a skill usage event.

    Called by pulse_save.py when agents report --skills_used.
    """
    USAGE_FILE.parent.mkdir(parents=True, exist_ok=True)
    data = _load_usage()

    if skill_name not in data:
        data[skill_name] = {"uses": 0, "successes": 0, "failures": 0}

    data[skill_name]["uses"] += 1
    if success:
        data[skill_name]["successes"] += 1
    else:
        data[skill_name]["failures"] += 1

    with _acquire(USAGE_FILE):
        USAGE_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")


def generate_report(top_n: int = 0) -> str:
    """Generate skill effectiveness report."""
    usage = _load_usage()
    all_skills = _list_all_skills()

    lines = [
        "Skill Effectiveness Report",
        "=" * 50,
        "",
    ]

    if not usage:
        lines.append("No skill usage data recorded yet.")
        lines.append("")
        lines.append("To start tracking:")
        lines.append("  pulse_save.py --agent <name> --skills-used \"DEBUG_WARLORD,GIT_SENTINEL\"")
        lines.append("")
        lines.append(f"Available skills: {len(all_skills)}")
        return "\n".join(lines)

    # Sort by uses
    sorted_skills = sorted(usage.items(), key=lambda x: -x[1].get("uses", 0))

    if top_n:
        sorted_skills = sorted_skills[:top_n]

    lines.append(f"{'Skill':<30} {'Uses':>5} {'Success':>8} {'Rate':>6}")
    lines.append("-" * 55)

    for skill, data in sorted_skills:
        uses = data.get("uses", 0)
        successes = data.get("successes", 0)
        rate = f"{successes/uses*100:.0f}%" if uses else "N/A"
        lines.append(f"{skill:<30} {uses:>5} {successes:>8} {rate:>6}")

    # Unused skills
    used_names = set(usage.keys())
    unused = [s for s in all_skills if s not in used_names]

    lines.append("")
    lines.append(f"Used: {len(used_names)}/{len(all_skills)} skills")
    lines.append(f"Unused: {len(unused)} skills")

    if unused:
        lines.append("")
        lines.append("Unused skills (consider deletion or enhancement):")
        for s in unused[:10]:
            lines.append(f"  - {s}")
        if len(unused) > 10:
            lines.append(f"  ... and {len(unused)-10} more")

    return "\n".join(lines)


def get_unused_skills() -> list[str]:
    """Get list of skills that have never been used."""
    usage = _load_usage()
    all_skills = _list_all_skills()
    used = set(usage.keys())
    return [s for s in all_skills if s not in used]


if __name__ == "__main__":
    if "--unused" in sys.argv:
        unused = get_unused_skills()
        if unused:
            print(f"Unused skills ({len(unused)}):")
            for s in unused:
                print(f"  - {s}")
        else:
            print("All skills have been used!")

    elif "--json" in sys.argv:
        print(json.dumps(_load_usage(), indent=2))

    else:
        top_n = 0
        if "--top" in sys.argv:
            idx = sys.argv.index("--top")
            if idx + 1 < len(sys.argv):
                top_n = int(sys.argv[idx + 1])
        print(generate_report(top_n))
