"""README section and badge generator for CLI tools and GitHub projects."""
from __future__ import annotations

from typing import Sequence


# ─── Badge generators ─────────────────────────────────────────────────────────

def badge(label: str, message: str, color: str = "blue", style: str = "flat") -> str:
    """Generate a shields.io badge in markdown."""
    l = label.replace("-", "--").replace("_", "__").replace(" ", "_")
    m = message.replace("-", "--").replace("_", "__").replace(" ", "_")
    return f"![{label}](https://img.shields.io/badge/{l}-{m}-{color}?style={style})"


def badge_pypi(package: str, style: str = "flat") -> str:
    return f"[![PyPI](https://img.shields.io/pypi/v/{package}?style={style})](https://pypi.org/project/{package}/)"


def badge_python(version: str = "3.10%2B", style: str = "flat") -> str:
    return f"![Python](https://img.shields.io/badge/python-{version}-blue?style={style})"


def badge_license(license_name: str = "MIT", style: str = "flat") -> str:
    return f"![License](https://img.shields.io/badge/license-{license_name}-green?style={style})"


def badge_github_actions(owner: str, repo: str, workflow: str = "CI", style: str = "flat") -> str:
    return (
        f"[![{workflow}](https://github.com/{owner}/{repo}/actions/workflows/ci.yml/badge.svg)]"
        f"(https://github.com/{owner}/{repo}/actions)"
    )


def badge_coverage(percent: int, style: str = "flat") -> str:
    color = "brightgreen" if percent >= 90 else "yellow" if percent >= 70 else "red"
    return f"![Coverage](https://img.shields.io/badge/coverage-{percent}%25-{color}?style={style})"


def badge_downloads(package: str, period: str = "month", style: str = "flat") -> str:
    return f"[![Downloads](https://img.shields.io/pypi/d{period[0]}/{package}?style={style})](https://pypi.org/project/{package}/)"


BADGE_PRESETS: dict[str, str] = {
    "maintained": badge("Maintained", "yes", "green"),
    "made-with-python": badge("Made with", "Python", "blue"),
    "made-with-typescript": badge("Made with", "TypeScript", "3178c6"),
    "made-with-rust": badge("Made with", "Rust", "dea584"),
    "made-with-go": badge("Made with", "Go", "00add8"),
    "docker": badge("Docker", "ready", "2496ed"),
    "contributions-welcome": badge("Contributions", "welcome", "brightgreen"),
    "prs-welcome": badge("PRs", "welcome", "brightgreen"),
    "ask-me-anything": badge("Ask me", "anything", "1abc9c"),
    "status-stable": badge("Status", "stable", "brightgreen"),
    "status-beta": badge("Status", "beta", "yellow"),
    "status-wip": badge("Status", "WIP", "orange"),
    "platform-linux": badge("Platform", "Linux", "informational"),
    "platform-macos": badge("Platform", "macOS", "informational"),
    "platform-windows": badge("Platform", "Windows", "informational"),
    "platform-cross": badge("Platform", "cross-platform", "informational"),
}


# ─── Section generators ───────────────────────────────────────────────────────

def header_section(
    title: str,
    description: str,
    badges: list[str] | None = None,
    logo: str = "",
    align: str = "center",
) -> str:
    """Generate the top header section of a README."""
    lines = []
    if align == "center":
        lines.append(f"<div align=\"center\">\n")
        if logo:
            lines.append(f"<img src=\"{logo}\" alt=\"{title} logo\" width=\"120\">\n")
        lines.append(f"# {title}\n")
        lines.append(f"*{description}*\n")
        if badges:
            lines.append("\n".join(badges))
            lines.append("")
        lines.append("</div>")
    else:
        lines.append(f"# {title}\n")
        lines.append(f"{description}\n")
        if badges:
            lines.append(" ".join(badges))
    return "\n".join(lines)


def toc(sections: list[str]) -> str:
    """Generate a Table of Contents."""
    lines = ["## Table of Contents\n"]
    for sec in sections:
        anchor = sec.lower().replace(" ", "-").replace("&", "").replace("/", "")
        lines.append(f"- [{sec}](#{anchor})")
    return "\n".join(lines)


def features_section(features: list[str], title: str = "Features") -> str:
    """Generate a Features section."""
    lines = [f"## {title}\n"]
    for feat in features:
        lines.append(f"- {feat}")
    return "\n".join(lines)


def installation_section(
    package: str,
    pip: bool = True,
    pipx: bool = False,
    brew: str = "",
    cargo: str = "",
    npm: str = "",
    git_clone: str = "",
    extra_steps: list[str] | None = None,
) -> str:
    """Generate an Installation section."""
    lines = ["## Installation\n"]

    if pip:
        lines.append("```bash")
        lines.append(f"pip install {package}")
        lines.append("```\n")

    if pipx:
        lines.append("Or install as an isolated tool:\n")
        lines.append("```bash")
        lines.append(f"pipx install {package}")
        lines.append("```\n")

    if brew:
        lines.append("Or via Homebrew:\n")
        lines.append("```bash")
        lines.append(f"brew install {brew}")
        lines.append("```\n")

    if cargo:
        lines.append("Or via Cargo:\n")
        lines.append("```bash")
        lines.append(f"cargo install {cargo}")
        lines.append("```\n")

    if npm:
        lines.append("Or via npm:\n")
        lines.append("```bash")
        lines.append(f"npm install -g {npm}")
        lines.append("```\n")

    if git_clone:
        lines.append("Or from source:\n")
        lines.append("```bash")
        lines.append(f"git clone {git_clone}")
        lines.append(f"cd {git_clone.rstrip('/').split('/')[-1]}")
        lines.append("pip install -e .")
        lines.append("```\n")

    if extra_steps:
        for step in extra_steps:
            lines.append(step)

    return "\n".join(lines)


def usage_section(
    commands: list[tuple[str, str]],
    title: str = "Usage",
    lang: str = "bash",
) -> str:
    """Generate a Usage section with command examples.

    commands: [(command, description), ...]
    """
    lines = [f"## {title}\n"]
    lines.append(f"```{lang}")
    for cmd, desc in commands:
        if desc:
            lines.append(f"# {desc}")
        lines.append(cmd)
        lines.append("")
    lines.append("```")
    return "\n".join(lines)


def config_section(
    options: list[tuple[str, str, str]],
    title: str = "Configuration",
    format: str = "table",
) -> str:
    """Generate a Configuration section.

    options: [(option, default, description), ...]
    """
    lines = [f"## {title}\n"]

    if format == "table":
        lines.append("| Option | Default | Description |")
        lines.append("|--------|---------|-------------|")
        for opt, default, desc in options:
            lines.append(f"| `{opt}` | `{default}` | {desc} |")
    else:
        for opt, default, desc in options:
            lines.append(f"- **`{opt}`** (default: `{default}`) — {desc}")

    return "\n".join(lines)


def api_section(
    endpoints: list[dict],
    title: str = "API Reference",
) -> str:
    """Generate an API reference section.

    endpoints: [{"method": str, "path": str, "description": str, "params": list}, ...]
    """
    lines = [f"## {title}\n"]

    for ep in endpoints:
        method = ep.get("method", "GET")
        path = ep.get("path", "/")
        desc = ep.get("description", "")
        params = ep.get("params", [])

        lines.append(f"### `{method} {path}`\n")
        if desc:
            lines.append(f"{desc}\n")
        if params:
            lines.append("**Parameters:**\n")
            lines.append("| Name | Type | Required | Description |")
            lines.append("|------|------|----------|-------------|")
            for p in params:
                req = "✓" if p.get("required") else ""
                lines.append(f"| `{p['name']}` | `{p.get('type', 'string')}` | {req} | {p.get('description', '')} |")
            lines.append("")

    return "\n".join(lines)


def contributing_section(
    repo_url: str = "",
    issues_url: str = "",
    pr_guide: str = "",
) -> str:
    """Generate a Contributing section."""
    lines = ["## Contributing\n"]
    lines.append("Contributions are welcome! Here's how to get started:\n")
    lines.append("1. Fork the repository")
    lines.append("2. Create your feature branch (`git checkout -b feature/amazing-feature`)")
    lines.append("3. Commit your changes (`git commit -m 'feat: add amazing feature'`)")
    lines.append("4. Push to the branch (`git push origin feature/amazing-feature`)")
    lines.append("5. Open a Pull Request\n")

    if issues_url:
        lines.append(f"Please report bugs or request features via [Issues]({issues_url}).\n")
    if pr_guide:
        lines.append(pr_guide)

    return "\n".join(lines)


def license_section(license_name: str = "MIT", year: str = "2024", author: str = "") -> str:
    """Generate a License section."""
    lines = ["## License\n"]
    lines.append(f"This project is licensed under the [{license_name} License](LICENSE).")
    if author:
        lines.append(f"\nCopyright © {year} {author}")
    return "\n".join(lines)


def acknowledgements_section(items: list[str], title: str = "Acknowledgements") -> str:
    """Generate an Acknowledgements / Credits section."""
    lines = [f"## {title}\n"]
    for item in items:
        lines.append(f"- {item}")
    return "\n".join(lines)


def quick_start_section(steps: list[tuple[str, str]], title: str = "Quick Start") -> str:
    """Generate a Quick Start section.

    steps: [(title, code_block), ...]
    """
    lines = [f"## {title}\n"]
    for i, (step_title, code) in enumerate(steps, 1):
        lines.append(f"**{i}. {step_title}**\n")
        lines.append("```bash")
        lines.append(code)
        lines.append("```\n")
    return "\n".join(lines)


def screenshot_section(
    screenshots: list[tuple[str, str]],
    title: str = "Screenshots",
) -> str:
    """Generate a Screenshots section.

    screenshots: [(alt_text, url), ...]
    """
    lines = [f"## {title}\n"]
    for alt, url in screenshots:
        lines.append(f"![{alt}]({url})\n")
    return "\n".join(lines)


def roadmap_section(
    done: list[str],
    todo: list[str],
    title: str = "Roadmap",
) -> str:
    """Generate a Roadmap section with checkboxes."""
    lines = [f"## {title}\n"]
    for item in done:
        lines.append(f"- [x] {item}")
    for item in todo:
        lines.append(f"- [ ] {item}")
    return "\n".join(lines)


# ─── Full README builder ───────────────────────────────────────────────────────

def build_readme(
    title: str,
    description: str,
    features: list[str] | None = None,
    install_cmd: str = "",
    usage_examples: list[tuple[str, str]] | None = None,
    contributing: bool = True,
    license_name: str = "MIT",
    author: str = "",
    badges: list[str] | None = None,
    extra_sections: list[str] | None = None,
) -> str:
    """Assemble a complete README.md."""
    sections = []

    # Header
    sections.append(header_section(title, description, badges=badges))
    sections.append("")

    # TOC items
    toc_items = []
    if features:
        toc_items.append("Features")
    if install_cmd:
        toc_items.append("Installation")
    if usage_examples:
        toc_items.append("Usage")
    if contributing:
        toc_items.append("Contributing")
    toc_items.append("License")

    if toc_items:
        sections.append(toc(toc_items))
        sections.append("")

    # Features
    if features:
        sections.append(features_section(features))
        sections.append("")

    # Installation
    if install_cmd:
        sections.append(installation_section(install_cmd))
        sections.append("")

    # Usage
    if usage_examples:
        sections.append(usage_section(usage_examples))
        sections.append("")

    # Extra sections
    for sec in (extra_sections or []):
        sections.append(sec)
        sections.append("")

    # Contributing
    if contributing:
        sections.append(contributing_section())
        sections.append("")

    # License
    sections.append(license_section(license_name, author=author))

    return "\n".join(sections)


# ─── CLI tool README template ─────────────────────────────────────────────────

def cli_tool_readme(
    tool_name: str,
    description: str,
    commands: list[tuple[str, str]],
    package_name: str = "",
    author: str = "",
    github_owner: str = "",
    github_repo: str = "",
) -> str:
    """Generate a complete README for a CLI tool."""
    pkg = package_name or tool_name.lower().replace(" ", "-")

    badges = [badge_python(), badge_license()]
    if github_owner and github_repo:
        badges.append(badge_github_actions(github_owner, github_repo))
    badges.append(badge("PRs", "welcome", "brightgreen"))

    features = [
        f"Command: `{tool_name}` — fast, composable CLI",
        "Cross-platform: Linux, macOS, Windows",
        "Zero config required — works out of the box",
    ]

    return build_readme(
        title=tool_name,
        description=description,
        features=features,
        install_cmd=pkg,
        usage_examples=commands,
        contributing=True,
        author=author,
        badges=badges,
    )
