"""技能扫描报告生成模块。

支持 JSON 和 Markdown 两种输出格式，生成技能注册表索引报告。
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

_SCRIPT_DIR = Path(__file__).resolve().parent
if str(_SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(_SCRIPT_DIR))

from models import ScanResult, SkillStatus


_STATUS_ICONS: dict[SkillStatus, str] = {
    SkillStatus.OK: "✅",
    SkillStatus.WARNING: "⚠️",
    SkillStatus.ERROR: "❌",
}

_SOURCE_TITLES: dict[str, str] = {
    "vendor": "Vendor Skills (flexloop chaos)",
    "local": "Local Skills (.agents/skills/)",
}


def _escape_md(text: str) -> str:
    if text:
        return text.replace("|", "\\|").replace("\n", " ")
    return ""


def _to_posix(path_str: str) -> str:
    return path_str.replace("\\", "/")


def generate_json_report(result: ScanResult, output_path: Path) -> None:
    output_path.parent.mkdir(parents=True, exist_ok=True)
    data = result.to_dict()
    data["stats"] = result.add_stats()
    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


def generate_markdown_report(result: ScanResult, output_path: Path) -> None:
    output_path.parent.mkdir(parents=True, exist_ok=True)
    stats = result.add_stats()
    lines: list[str] = []

    lines.append("# Skill Registry Index")
    lines.append("")

    lines.append("## Metadata")
    lines.append("")
    lines.append(f"- **Scan Time**: {result.scan_time}")
    lines.append("- **Scan Directories**:")
    for d in result.scan_dirs:
        lines.append(f"  - `{_to_posix(d)}`")
    lines.append("- **Generator**: skill-auto-loader")
    lines.append("")

    lines.append("## Summary")
    lines.append("")
    lines.append(f"- **Total Skills**: {stats['total']}")
    lines.append(f"- ✅ **OK**: {stats['ok']}")
    lines.append(f"- ⚠️ **Warnings**: {stats['warning']}")
    lines.append(f"- ❌ **Errors**: {stats['error']}")
    lines.append(f"- 🔀 **Conflicts**: {stats['conflicts']}")
    lines.append("")

    skills_by_source: dict[str, list] = {}
    for skill in result.skills:
        source = skill.source
        if source not in skills_by_source:
            skills_by_source[source] = []
        skills_by_source[source].append(skill)

    for source in ["vendor", "local"]:
        if source not in skills_by_source:
            continue
        title = _SOURCE_TITLES.get(source, source.title())
        lines.append(f"## {title}")
        lines.append("")
        skills = sorted(skills_by_source[source], key=lambda s: s.name.lower())
        for skill in skills:
            icon = _STATUS_ICONS.get(skill.status, "❓")
            if skill.version:
                version_str = f" (v{skill.version})"
            else:
                version_str = ""
            desc_str = f" - {skill.description}" if skill.description else ""
            path_str = _to_posix(skill.skill_path)
            lines.append(f"- {icon} **{skill.name}**{version_str}{desc_str} → `{path_str}`")
            if skill.issues:
                for issue in skill.issues:
                    lines.append(f"  - ⚠️ {issue}")
        lines.append("")

    if result.errors:
        lines.append("## Errors")
        lines.append("")
        lines.append("| File | Type | Message | Suggestion |")
        lines.append("|------|------|---------|------------|")
        for err in result.errors:
            file_str = _to_posix(_escape_md(err.file_path))
            type_str = _escape_md(err.error_type)
            msg_str = _escape_md(err.message)
            sug_str = _escape_md(err.suggestion)
            lines.append(f"| `{file_str}` | {type_str} | {msg_str} | {sug_str} |")
        lines.append("")

    if result.conflicts:
        lines.append("## Name Conflicts")
        lines.append("")
        for conflict in result.conflicts:
            name = conflict["name"]
            count = conflict["count"]
            files = conflict["files"]
            lines.append(f"- **{name}** ({count} occurrences):")
            for f in files:
                lines.append(f"  - `{_to_posix(f)}`")
        lines.append("")

    lines.append("---")
    lines.append("")
    lines.append("_Generated by skill-auto-loader_")
    lines.append("")

    with open(output_path, "w", encoding="utf-8") as f:
        f.write("\n".join(lines))


def generate_report(result: ScanResult, output_path: Path, fmt: str = "json") -> None:
    suffix = output_path.suffix.lower()
    if suffix == ".json":
        fmt = "json"
    elif suffix in (".md", ".markdown"):
        fmt = "markdown"

    fmt = fmt.lower()
    if fmt in ("md", "markdown"):
        generate_markdown_report(result, output_path)
    else:
        generate_json_report(result, output_path)
