"""autopsy.py — ICU escalation report generator.

When max feedback attempts exhaust, generates a structured autopsy
report for the Production Console Dailies queue and morning briefing.
"""
import json
import time
from pathlib import Path


def generate_autopsy_report(
    shot_id: str,
    project_id: str,
    attempt_history: list,
    final_verdict,
    shot_data: dict,
) -> dict:
    """Generate a full ICU autopsy report.

    The report contains all attempted fixes, their outcomes, the final
    gate verdict, and recommended human actions.
    """
    attempts_summary = []
    total_cost = 0.0

    for attempt in attempt_history:
        total_cost += attempt.cost
        attempts_summary.append({
            "number": attempt.attempt_number,
            "strategy": attempt.strategy.value,
            "gate": attempt.gate_failed,
            "reason": attempt.failure_reason[:200],
            "result": attempt.result,
            "cost": round(attempt.cost, 4),
        })

    recommended_actions = _recommend_actions(attempt_history, final_verdict)

    return {
        "shot_id": shot_id,
        "project": project_id,
        "status": "ICU",
        "timestamp": time.time(),
        "attempts": attempts_summary,
        "attempt_count": len(attempts_summary),
        "final_verdict": {
            "gate": getattr(final_verdict, 'gate_name', 'unknown'),
            "reason": getattr(final_verdict, 'reason', 'unknown')[:200],
            "severity": getattr(final_verdict, 'details', {}).get('total_severity', 0),
        },
        "total_feedback_cost": round(total_cost, 4),
        "recommended_actions": recommended_actions,
    }


def _recommend_actions(attempt_history: list, final_verdict) -> list[str]:
    """Generate human-readable recommended actions based on failure patterns."""
    actions = []
    gate = getattr(final_verdict, 'gate_name', '')

    if 'identity' in gate.lower():
        actions.append("Check casting refs — the hero ref may need updating")
        actions.append("Consider re-running casting with updated turnarounds")
    elif 'wardrobe' in gate.lower():
        actions.append("Wardrobe spec may be ambiguous — add explicit clothing description")
        actions.append("Consider adding a wardrobe-specific ref image")
    elif 'lighting' in gate.lower():
        actions.append("Lighting layer may need more explicit directional instructions")
        actions.append("Check if location ref has conflicting lighting")
    elif 'anatomy' in gate.lower() or 'gate_1' in gate.lower():
        actions.append("Persistent anatomy issues — try a different composition (wider shot, hands hidden)")
        actions.append("Consider simplifying the pose to reduce generation complexity")
    else:
        actions.append("Review the failed outputs and gate verdicts manually")
        actions.append("Consider a complete prompt rewrite for this shot")

    return actions


def save_autopsy_to_project(autopsy: dict, project_root: Path) -> Path:
    """Save autopsy report to project's ICU queue."""
    from recoil.core.paths import ProjectPaths
    icu_dir = ProjectPaths.from_root(project_root).visual_state_dir / "icu"
    icu_dir.mkdir(parents=True, exist_ok=True)
    filename = f"{autopsy['shot_id']}_autopsy.json"
    path = icu_dir / filename
    with open(path, "w") as f:
        json.dump(autopsy, f, indent=2)
    return path
