from __future__ import annotations

import json
import subprocess
from collections import defaultdict


def get_task_group(task_name):
    if task_name.startswith("pytest-diracx"):
        return "DiracX"
    if task_name.startswith("pytest-gubbins"):
        return "Gubbins"
    if task_name.startswith("mkdocs"):
        return "Documentation"
    if task_name == "pre-commit":
        return "Pre-commit"
    if task_name == "generate-client":
        return "Client Generation"
    if task_name == "shellcheck":
        return "Shellcheck"
    return "Default"


def main():
    """Generate the pixi-tasks.md file."""
    result = subprocess.run(
        ["pixi", "task", "list", "--json"],  # noqa: S607
        capture_output=True,
        text=True,
    )
    environments = json.loads(result.stdout)

    tasks_by_group = defaultdict(list)
    for env in environments:
        for feature in env["features"]:
            for task in feature["tasks"]:
                group = get_task_group(task["name"])
                tasks_by_group[group].append(task)

    with open("docs/dev/reference/pixi-tasks.md", "w") as f:
        f.write("# Pixi Tasks\n\n")
        f.write("*This page is auto-generated. Do not edit directly.*\n\n")
        f.write("DiracX uses [Pixi](https://pixi.dev/) as package manager\n")
        f.write("This page documents the available pixi tasks.\n\n")

        for group in sorted(tasks_by_group.keys()):
            f.write(f"## {group} Tasks\n\n")
            # Remove duplicates
            tasks = list({v["name"]: v for v in tasks_by_group[group]}.values())
            for task in sorted(tasks, key=lambda x: x["name"]):
                description = (
                    task.get("description") or task.get("cmd") or "No description"
                )
                f.write(f"- `{task['name']}`: {description}\n")
            f.write("\n")

        f.write("Generated by .github/workflows/generate_pixi_tasks_doc.py\n")


if __name__ == "__main__":
    main()
