#!/usr/bin/env python3
import subprocess
import tempfile
import time
from pathlib import Path
from typing import Iterator, Iterable

from manifestoo_core.addon import Addon, AddonNotFound
from manifestoo_core.odoo_series import OdooEdition

SERIES = [
    # branch,  enterprise, target
    ("19.0", True, None),
    ("18.0", True, None),
    ("17.0", True, None),
    ("16.0", True, None),
    # ("15.0", True, None),
    # ("14.0", True, None),
    # ("13.0", True, None),
    # ("12.0", True, None),
    # ("11.0", True, None),
    # ('10.0', True, None),
    # ('9.0', True, None),
    # ('8.0', False, None),
]


def _list_addons(addons_dirs: Iterable[Path]) -> Iterator[str]:
    for addons_dir in addons_dirs:
        for addon_dir in addons_dir.iterdir():
            try:
                yield Addon.from_addon_dir(addon_dir, allow_not_installable=True).name
            except AddonNotFound:
                pass


def _write_addons_list(addons_dirs: Iterable[Path], suffix: str) -> None:
    list_path = (
        Path(__file__).parent
        / "src"
        / "manifestoo_core"
        / "core_addons"
        / f"addons-{suffix}.txt"
    )
    with list_path.open("w") as f:
        print("# generated on", time.asctime(), file=f)
        for addon_name in sorted(_list_addons(addons_dirs)):
            print(addon_name, file=f)


def check_call(*cmd: str) -> None:
    print(" ".join(cmd))
    subprocess.check_call(cmd)


def check_output(*cmd: str) -> str:
    print(" ".join(cmd))
    return subprocess.check_output(cmd, text=True)


def main() -> None:
    for branch, enterprise, target in SERIES:
        with tempfile.TemporaryDirectory() as tmpdir:
            check_call(
                "git",
                "clone",
                "--depth=1",
                "--branch",
                branch,
                "https://github.com/odoo/odoo",
                tmpdir,
            )
            _write_addons_list(
                [
                    Path(tmpdir)
                    / ("openerp" if float(branch) < 10 else "odoo")
                    / "addons",
                    Path(tmpdir) / "addons",
                ],
                f"{target or branch}-{OdooEdition.CE.value}",
            )
        if enterprise:
            with tempfile.TemporaryDirectory() as tmpdir:
                check_call(
                    "git",
                    "clone",
                    "--depth=1",
                    "--branch",
                    branch,
                    "git@github.com:odoo/enterprise",
                    tmpdir,
                )
                _write_addons_list(
                    [Path(tmpdir)],
                    f"{target or branch}-{OdooEdition.EE.value}",
                )


def pr():
    assert Path("news").is_dir()
    check_call("git", "checkout", "-B", "update-core-addon-lists", "origin/main")
    check_call("git", "add", "src/manifestoo_core/core_addons")
    check_call("git", "commit", "-m", "Update core addon lists")
    check_call("git", "push", "-f", "origin")
    output = check_output(
        "gh", "pr", "create", "--title", "Update core addon lists", "--body", ""
    )
    pr = output.strip().rpartition("/")[-1]
    news_path = Path("news") / f"{pr}.feature"
    news_path.write_text("Update core addon lists.\n")
    check_call("git", "add", str(news_path))
    check_call("git", "commit", "--amend", "--no-edit")
    check_call("git", "push", "-f")


if __name__ == "__main__":
    main()
    pr()
