from pathlib import Path
from datetime import datetime, timezone


def generate_report(
    run_id: str,
    results: list,
    scores: dict,
    overall: float,
    output_path: str = None,
    llm_insight=None,
) -> str:
    band = "🟢 HEALTHY" if overall >= 85 else "🟡 DEGRADED" if overall >= 65 else "🔴 CRITICAL"
    timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")

    critical_issues = []
    all_recommendations = []
    metrics_section = ""

    for result in results:
        for issue in getattr(result, "issues", []):
            if issue.get("severity") == "high":
                critical_issues.append(f"- **[{result.agent.upper()}]** {issue['description']}")
            rec = issue.get("recommendation")
            if rec:
                all_recommendations.append(f"- **{result.agent.title()}**: {rec}")
        m = getattr(result, "metrics", {})
        if m:
            metrics_section += f"\n### {result.agent.title()}\n"
            for k, v in m.items():
                if not isinstance(v, list):
                    metrics_section += f"- `{k}`: {v}\n"

    critical_block = "\n".join(critical_issues) if critical_issues else "- None"
    recs_block = "\n".join(all_recommendations) if all_recommendations else "- System within acceptable parameters"

    llm_section = ""
    if llm_insight:
        llm_section = _format_llm_section(llm_insight)

    report = f"""# 🔍 finobs — Observability Audit

**Run ID:** `{run_id}`
**Timestamp:** {timestamp}
**Overall Score:** {overall}/100 — {band}

---

## Score Summary

| Dimension       | Weight | Score       |
|-----------------|--------|-------------|
| Performance     | 25%    | {scores.get('performance', 0)}/100 |
| Quality         | 25%    | {scores.get('quality', 0)}/100     |
| Cost            | 20%    | {scores.get('cost', 0)}/100        |
| Stability       | 15%    | {scores.get('stability', 0)}/100   |
| RAG             | 15%    | {scores.get('rag', 0)}/100         |
| **Overall**     |        | **{overall}/100**  |

---

## Critical Issues

{critical_block}

---

## Key Metrics
{metrics_section}

---

## Actionable Recommendations

{recs_block}
{llm_section}
---

*Generated by [finobs](https://github.com/tu-org/finobs)*
"""

    path = output_path or f"AUDIT-{run_id}.md"
    Path(path).write_text(report)
    return path


def _format_llm_section(insight) -> str:
    fixes_md = ""
    for fix in insight.fixes:
        priority_badge = {"high": "🔴", "medium": "🟡", "low": "🟢"}.get(fix["priority"], "•")
        fixes_md += f"- {priority_badge} **[{fix.get('area', 'general')}]** {fix['description']}\n"
        if fix.get("example"):
            fixes_md += f"  > {fix['example']}\n"

    patterns_md = "\n".join(f"- {p}" for p in insight.patterns) or "- None detected"

    return f"""
---

## 🤖 Claude Semantic Analysis

**Root Cause:** {insight.root_cause}

**Confidence:** {insight.confidence:.0%} | **Tokens used:** {insight.tokens_used:,}

### Patterns Detected

{patterns_md}

### Recommended Fixes

{fixes_md or "- No additional fixes suggested"}
"""
