"""Decision Audit Logger - Tracks decisions and outcomes."""

from __future__ import annotations

import json
import uuid
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any


@dataclass
class Decision:
    """A logged decision."""

    id: str
    decision: str
    context: str
    expected: str
    timestamp: str
    outcome: str | None = None
    correct: bool | None = None


class DecisionAuditLogger:
    """Tracks decisions and their outcomes for auditing."""

    def __init__(self, db_path: str | None = None) -> None:
        from oclawma.config import get_workspace_dir

        self.db_path = Path(db_path or str(get_workspace_dir() / "memory" / "decisions.json"))

    def _init_db(self) -> None:
        """Initialize database if it doesn't exist."""
        if not self.db_path.exists():
            self.db_path.parent.mkdir(parents=True, exist_ok=True)
            self._save_db({"decisions": []})

    def _load_db(self) -> dict:
        """Load database."""
        try:
            with open(self.db_path, encoding="utf-8") as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            return {"decisions": []}

    def _save_db(self, data: dict) -> None:
        """Save database."""
        with open(self.db_path, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2)

    def _generate_id(self) -> str:
        """Generate a unique ID."""
        return str(uuid.uuid4())[:8]

    def log_decision(self, decision: str, context: str = "", expected: str = "success") -> str:
        """Log a new decision."""
        self._init_db()
        data = self._load_db()

        entry = {
            "id": self._generate_id(),
            "decision": decision,
            "context": context,
            "expected": expected,
            "timestamp": datetime.now().isoformat(),
            "outcome": None,
            "correct": None,
        }

        data["decisions"].append(entry)
        self._save_db(data)

        return entry["id"]

    def record_outcome(self, decision_id: str, outcome: str, correct: bool) -> bool:
        """Record the outcome of a decision."""
        self._init_db()
        data = self._load_db()

        for d in data["decisions"]:
            if d["id"] == decision_id:
                d["outcome"] = outcome
                d["correct"] = correct
                self._save_db(data)
                return True

        return False

    def get_decision(self, decision_id: str) -> dict | None:
        """Get a specific decision."""
        data = self._load_db()
        for d in data["decisions"]:
            if d["id"] == decision_id:
                return d
        return None

    def get_stats(self) -> dict[str, Any]:
        """Get decision statistics."""
        data = self._load_db()
        decisions = data.get("decisions", [])

        with_outcome = [d for d in decisions if d.get("outcome") is not None]
        correct_count = sum(1 for d in with_outcome if d.get("correct"))

        accuracy = (correct_count / len(with_outcome) * 100) if with_outcome else 0

        return {
            "total": len(decisions),
            "with_outcome": len(with_outcome),
            "pending": len(decisions) - len(with_outcome),
            "correct": correct_count,
            "incorrect": len(with_outcome) - correct_count,
            "accuracy": round(accuracy, 1),
        }

    def generate_report(self) -> None:
        """Generate a report of decisions."""
        stats = self.get_stats()

        print("\n🎲 Decision Audit Report")
        print("─" * 30)
        print(f"Total decisions: {stats['total']}")
        print(f"With outcomes: {stats['with_outcome']}")
        print(f"Pending: {stats['pending']}")
        print(f"Accuracy: {stats['accuracy']}%")

    def list_recent(self, limit: int = 10) -> list[dict]:
        """List recent decisions."""
        data = self._load_db()
        return data.get("decisions", [])[-limit:]

    def print_recent(self, limit: int = 10) -> None:
        """Print recent decisions."""
        recent = self.list_recent(limit)

        print(f"\n📋 Last {len(recent)} decisions:")
        for d in recent:
            status = "✅" if d.get("correct") else "❌" if d.get("outcome") else "⏳"
            print(f"{status} [{d['id'][:8]}] {d['decision'][:50]}")
            if d.get("outcome"):
                print(f"   Outcome: {d['outcome']}")


def main() -> None:
    """CLI entry point."""
    import sys

    logger = DecisionAuditLogger()
    command = sys.argv[1] if len(sys.argv) > 1 else "report"

    if command == "log":
        decision = sys.argv[2] if len(sys.argv) > 2 else "unnamed"
        context = sys.argv[3] if len(sys.argv) > 3 else ""
        expected = sys.argv[4] if len(sys.argv) > 4 else "success"
        decision_id = logger.log_decision(decision, context, expected)
        print(f"Logged decision: {decision_id}")

    elif command == "outcome":
        decision_id = sys.argv[2] if len(sys.argv) > 2 else None
        outcome = sys.argv[3] if len(sys.argv) > 3 else ""
        correct_str = sys.argv[4].lower() if len(sys.argv) > 4 else "true"
        correct = correct_str in ("true", "yes", "1")

        if decision_id:
            if logger.record_outcome(decision_id, outcome, correct):
                print(f"✅ Recorded outcome for {decision_id}")
            else:
                print(f"❌ Decision {decision_id} not found")
        else:
            print("Usage: outcome [id] [outcome] [correct]")

    elif command == "report":
        logger.generate_report()

    elif command == "recent":
        logger.print_recent()

    elif command == "get":
        decision_id = sys.argv[2] if len(sys.argv) > 2 else None
        if decision_id:
            decision = logger.get_decision(decision_id)
            if decision:
                print(json.dumps(decision, indent=2))
            else:
                print(f"Decision {decision_id} not found")
        else:
            print("Usage: get [id]")

    else:
        print("Decision Audit Logger")
        print("Usage:")
        print("  log [decision] [context] [expected]  - Log a decision")
        print("  outcome [id] [outcome] [correct]     - Record outcome")
        print("  report                               - Generate report")
        print("  recent                               - Show recent decisions")
        print("  get [id]                             - Get specific decision")


if __name__ == "__main__":
    main()
