#!/usr/bin/env python3

import json
import os
import pathlib

ROOT_DIR = ".."
USER_EXAMPLES_JSON = "docs/pyxel_user_examples.json"

PAGE_HEADER = """\
[![Downloads](https://static.pepy.tech/personalized-badge/pyxel?period=total&units=international_system&left_color=grey&right_color=blue&left_text=PyPI%20downloads)](https://pypi.org/project/pyxel/)
[![GitHub Repo stars](https://img.shields.io/github/stars/kitao/pyxel?style=social)](https://github.com/kitao/pyxel)
[![GitHub forks](https://img.shields.io/github/forks/kitao/pyxel?style=social)](https://github.com/kitao/pyxel)
[![GitHub Sponsors](https://img.shields.io/github/sponsors/kitao?label=Sponsor%20me&logo=github%20sponsors&style=social)](https://github.com/sponsors/kitao)

[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/H2H27VDKD)

[Pyxel](https://github.com/kitao/pyxel), a retro game engine for Python, is collecting user examples. If you have created a project with Pyxel, please post it [here](https://github.com/kitao/pyxel/issues/639).
"""
NUM_EXAMPLES_PER_PAGE = 20


def generate_navigation_links(page_ranges, cur_start_id, cur_end_id):
    latest_start_id, _ = page_ranges[-1]
    links = []

    for start_id, end_id in reversed(page_ranges):
        if start_id == latest_start_id:
            if start_id == cur_start_id:
                links.append(f"-{start_id}")
            else:
                links.append(f"[-{start_id}](Pyxel-User-Examples)")
        elif start_id == cur_start_id and end_id == cur_end_id:
            links.append(f"{str(end_id).zfill(3)}-{str(start_id).zfill(3)}")
        else:
            links.append(
                f"[{str(end_id).zfill(3)}-{str(start_id).zfill(3)}](Pyxel-User-Examples-({str(end_id).zfill(3)}%E2%80%90{str(start_id).zfill(3)}))"
            )

    return "&emsp;".join(links)


def generate_markdown_table(entries):
    markdown_lines = ["| Description | Screen Image |", "| --- | --- |"]

    for entry in entries:
        id = entry["id"]
        title = (
            f"[{entry['title']}]({entry['site']})"
            if "site" in entry
            else entry["title"]
        )
        author = (
            f"[{entry['author']}]({entry['contact']})"
            if "contact" in entry
            else entry["author"]
        )
        desc = entry["desc"]
        image = f'<img src="{entry["image"]}" width="320">'
        markdown_lines.append(f"| #{id}<br>{title} by {author}<br>{desc} | {image} |")

    return "\n".join(markdown_lines)


def generate_examples_markdown():
    os.chdir(pathlib.Path(__file__).parent / ROOT_DIR)

    with open(USER_EXAMPLES_JSON, "r", encoding="utf-8") as f:
        data = json.load(f)

    entries = {entry["id"]: entry for entry in data["entries"]}
    max_id = max(entries.keys())
    min_id = min(entries.keys())

    page_ranges = [
        (i, min(i + NUM_EXAMPLES_PER_PAGE - 1, max_id))
        for i in range(min_id, max_id + 1, NUM_EXAMPLES_PER_PAGE)
    ]

    for start_id, end_id in reversed(page_ranges):
        subset = [entries[i] for i in range(start_id, end_id + 1) if i in entries]
        if not subset:
            continue

        subset.sort(key=lambda x: x["id"], reverse=True)
        filename = (
            f"pyxel_user_examples_{str(end_id).zfill(3)}_{str(start_id).zfill(3)}.md"
        )

        navigation_links = generate_navigation_links(page_ranges, start_id, end_id)
        markdown_content = f"{PAGE_HEADER}\n\n{navigation_links}\n\n{generate_markdown_table(subset)}\n\n{navigation_links}\n"

        with open(filename, "w", encoding="utf-8") as f:
            f.write(markdown_content)


if __name__ == "__main__":
    generate_examples_markdown()
