from __future__ import annotations
import json
from pathlib import Path
from .runner import RunResult
from fixit.core.paths import reports_dir

def _read_json_file(p: Path) -> list[dict]:
    if not p.exists():
        return []
    try:
        return json.loads(p.read_text(encoding="utf-8"))
    except Exception:
        return []

def write_html_report(res: RunResult) -> Path:
    out_dir = reports_dir()
    out_dir.mkdir(parents=True, exist_ok=True)
    # Read advice if present
    advice_path = out_dir / "advice.json"
    advices = _read_json_file(advice_path)

    # Build LLM section
    llm_html = ""
    if advices:
        rows = []
        for a in advices:
            test_id = a.get("test_id","")
            failure_type = a.get("failure_type","")
            rc = a.get("root_cause",{})
            summary = rc.get("summary","")
            details = rc.get("details","")
            prio = (a.get("fix_suggestions") or [{}])[0].get("priority","n/a")
            conf = a.get("confidence_score","-")
            
            # Build patches section if available
            patches_html = ""
            code_patches = a.get("code_patches", [])
            if code_patches:
                patches_html = "<div><b>LLM Code Patches:</b></div>"
                for i, patch in enumerate(code_patches, 1):
                    file_name = patch.get("file", "unknown")
                    diff_content = patch.get("diff", "")
                    patches_html += f"""
                    <div style='margin:4px 0;'>
                        <div style='font-weight:bold;color:#0066cc;'>📄 {file_name}</div>
                        <pre style='background:#f8f8f8;padding:8px;border:1px solid #ddd;margin:4px 0;overflow-x:auto;font-size:12px;'><code>{_escape_html(diff_content)}</code></pre>
                    </div>
                    """
            
            rows.append(f"""
            <div style='margin:12px 0;padding:12px;border:1px solid #ddd;border-radius:4px;'>
                <div style='margin-bottom:8px;'>
                    <span style='font-weight:bold;color:#333;'>{test_id}</span>
                    <span style='margin-left:16px;color:#666;'>Type: {failure_type}</span>
                    <span style='margin-left:16px;color:#666;'>Priority: {prio}</span>
                    <span style='margin-left:16px;color:#666;'>Confidence: {conf}</span>
                </div>
                <div style='margin:6px 0;'><b>Summary:</b> {summary}</div>
                <div style='margin:6px 0;'><b>Details:</b> 
                    <pre style='white-space:pre-wrap;background:#f5f5f5;padding:6px;border-left:3px solid #ccc;'>{details}</pre>
                </div>
                {patches_html}
            </div>
            """)
        llm_html = "<h2>🤖 LLM Explanations & Code Patches</h2>" + "".join(rows)

    html = f"""<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Fixit Report</title>
    <style>
        body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; margin: 2rem; line-height: 1.5; }}
        .ok {{ color: green; }}
        .bad {{ color: red; }}
        h1, h2 {{ color: #333; }}
        h2 {{ border-bottom: 2px solid #eee; padding-bottom: 8px; }}
        pre {{ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; }}
        .diff-line-add {{ background-color: #d4edda; color: #155724; }}
        .diff-line-remove {{ background-color: #f8d7da; color: #721c24; }}
        .diff-line-context {{ background-color: #f8f9fa; }}
    </style>
</head>
<body>
    <h1>🔧 Fixit Report</h1>
    <p>Status: <b class="{ 'ok' if res.exit_code == 0 else 'bad' }">{ '✅ PASS' if res.exit_code == 0 else '❌ FAIL' }</b></p>
    <p>📊 Results: <b>{res.passed}</b> passed, <b>{res.failed}</b> failed, <b>{res.total}</b> total</p>
    
    {llm_html}
    
    <h2>📋 Raw Test Output</h2>
    <pre style="background:#f7f7f7;padding:1rem;border:1px solid #ddd;white-space:pre-wrap;overflow-x:auto;">{_escape_html((res.raw_output or '')[:10000])}</pre>
    
    <footer style="margin-top:2rem;padding-top:1rem;border-top:1px solid #eee;color:#666;font-size:0.9em;">
        Generated by Fixit.AI • {_get_timestamp()}
    </footer>
</body>
</html>
"""
    p = out_dir / "index.html"
    p.write_text(html, encoding="utf-8")
    return p

def _escape_html(text: str) -> str:
    """Escape HTML special characters."""
    if not text:
        return ""
    return (text
        .replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
        .replace("'", "&#39;"))

def _get_timestamp() -> str:
    """Get current timestamp for footer."""
    from datetime import datetime
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")