from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Iterable


@dataclass
class ReviewRenderPayload:
    mode: str
    file_summary: str
    section_order: Iterable[tuple[str, str]]
    sections: dict[str, list[tuple[str, str]]]
    has_findings: bool = False
    title: str | None = None
    notice: str | None = None


_last_payload: ReviewRenderPayload | None = None


def capture_review_payload(payload: ReviewRenderPayload) -> None:
    global _last_payload
    _last_payload = payload


def clear_last_review_payload() -> None:
    global _last_payload
    _last_payload = None


def should_prompt_markdown_save() -> bool:
    return bool(_last_payload and _last_payload.has_findings)


def save_last_review_markdown(base_dir: Path | None = None) -> Path | None:
    if _last_payload is None:
        return None
    target_dir = base_dir or (Path.cwd() / "gar-md")
    target_dir.mkdir(parents=True, exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    filename = f"gar-review-{timestamp}.md"
    path = target_dir / filename
    _write_markdown_stub(path, _last_payload)
    return path


def _write_markdown_stub(path: Path, payload: ReviewRenderPayload) -> None:
    title = payload.title or f"{payload.mode.capitalize()} Review"
    lines: list[str] = []
    lines.append(f"# {title}")
    lines.append("")
    lines.append("## Summary")
    lines.append(f"- Mode: {payload.mode}")
    lines.append(f"- File Summary: {payload.file_summary}")
    if payload.notice:
        lines.append(f"- Notice: {payload.notice}")
    lines.append("")

    label_map = {key: label for key, label in payload.section_order}
    section_keys = [key for key, _label in payload.section_order]
    has_items = any(payload.sections.get(key) for key in section_keys)

    if not has_items:
        lines.append("## Findings")
        lines.append("")
        lines.append("- 없음")
        path.write_text("\n".join(lines) + "\n", encoding="utf-8")
        return

    lines.append("## Findings")
    lines.append("")
    for key in section_keys:
        entries = payload.sections.get(key, [])
        if not entries:
            continue
        section_title = label_map.get(key, key)
        lines.append(f"### {section_title}")
        lines.append("")
        for risk, fix in entries:
            risk_text = risk.strip() if risk else ""
            fix_text = fix.strip() if fix else ""
            if risk_text:
                lines.append(f"- **Risk**: {risk_text}")
            if fix_text:
                lines.append(f"  - **Fix**: {fix_text}")
            if not risk_text and not fix_text:
                lines.append("- (내용 없음)")
            lines.append("")
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
