"""Generate WordPress-ready markdown articles from ProjectProfile data."""

from __future__ import annotations

from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, List

from .article_sections import (
    render_architecture,
    render_api_surface,
    render_build_targets,
    render_changelog,
    render_dependencies,
    render_docker,
    render_footer,
    render_frontmatter,
    render_header,
    render_metrics,
    render_maturity,
    render_overview,
    render_tech_stack,
    render_usage,
)

if TYPE_CHECKING:
    from todocs.core import ProjectProfile


class ArticleGenerator:
    """Generate markdown articles for WordPress from analyzed project profiles."""

    def __init__(self, org_name: str = "WronAI", org_url: str = "https://github.com/wronai"):
        self.org_name = org_name
        self.org_url = org_url
        self.generated_at = datetime.now().strftime("%Y-%m-%d")

    def generate(self, profile: "ProjectProfile", output_path: Path) -> None:
        """Generate a single project article."""
        md = self._render_article(profile)
        output_path.write_text(md, encoding="utf-8")

    def generate_index(self, profiles: List["ProjectProfile"], output_path: Path) -> None:
        """Generate an index/overview article listing all projects."""
        md = self._render_index(profiles)
        output_path.write_text(md, encoding="utf-8")

    def _render_article(self, p: "ProjectProfile") -> str:
        """Render complete article by combining all sections."""
        sections = [
            render_frontmatter(p, self.org_name, self.generated_at),
            render_header(p, self.org_url),
            render_overview(p, self.org_name),
            render_tech_stack(p),
            render_architecture(p),
            render_metrics(p),
            render_maturity(p),
            render_dependencies(p),
            render_api_surface(p),
            render_build_targets(p),
            render_docker(p),
            render_changelog(p),
            render_usage(p),
            render_footer(self.generated_at),
        ]
        return "\n\n".join(s for s in sections if s)

    def _render_index(self, profiles: List["ProjectProfile"]) -> str:
        """Generate organization portfolio index."""
        sections = []

        # Frontmatter
        sections.append("\n".join([
            "---",
            f'title: "{self.org_name} — Organization Project Portfolio"',
            f'slug: "{self.org_name.lower()}-portfolio"',
            f'date: "{self.generated_at}"',
            f'category: "Portfolio"',
            f'generated_by: "todocs v0.1.0"',
            "---",
        ]))

        sections.append(f"# {self.org_name} — Project Portfolio")
        sections.append(
            f"Overview of **{len(profiles)}** projects in the {self.org_name} organization, "
            f"analyzed on {self.generated_at}."
        )

        # Summary stats
        total_lines = sum(p.code_stats.source_lines for p in profiles)
        total_files = sum(p.code_stats.source_files for p in profiles)
        avg_maturity = sum(p.maturity.score for p in profiles) / len(profiles) if profiles else 0

        sections.append("\n".join([
            "## Summary Statistics",
            "",
            f"- **Total projects**: {len(profiles)}",
            f"- **Total source files**: {total_files:,}",
            f"- **Total source lines**: {total_lines:,}",
            f"- **Average maturity score**: {avg_maturity:.0f}/100",
        ]))

        # Group by category
        categories: dict[str, list] = {}
        for p in profiles:
            categories.setdefault(p.category, []).append(p)

        for cat, projs in sorted(categories.items()):
            lines = [f"## {cat}"]
            lines.append("")
            lines.append("| Project | Version | Grade | Language | Source Lines | Tests |")
            lines.append("|---------|---------|:-----:|----------|------------:|:-----:|")

            for p in sorted(projs, key=lambda x: x.name):
                ver = p.metadata.version or "—"
                grade = p.maturity.grade
                lang = p.tech_stack.primary_language
                sloc = f"{p.code_stats.source_lines:,}"
                tests = "✅" if p.maturity.has_tests else "❌"
                link = f"[{p.name}]({p.name}.md)"
                lines.append(f"| {link} | {ver} | {grade} | {lang} | {sloc} | {tests} |")

            sections.append("\n".join(lines))

        # Maturity distribution
        grades: dict[str, int] = {}
        for p in profiles:
            grades[p.maturity.grade] = grades.get(p.maturity.grade, 0) + 1

        grade_lines = ["## Maturity Distribution", ""]
        for g in ["A+", "A", "B+", "B", "C+", "C", "D", "D-", "F"]:
            count = grades.get(g, 0)
            if count:
                bar = "█" * count
                grade_lines.append(f"  {g:>3}: {bar} {count}")
        sections.append("\n".join(grade_lines))

        # Footer
        sections.append("\n".join([
            "---",
            "",
            f"*Generated by [todocs](https://github.com/wronai/todocs) v0.1.0 on {self.generated_at}.*",
        ]))

        return "\n\n".join(sections)
