#!/usr/bin/env python3
"""Archive PrestaShop amchoose prête pour livraison WooCommerce et installation."""

from __future__ import annotations

import shutil
import zipfile
from pathlib import Path

MODULE_SRC = Path("/Users/arnaudmerigeau/Locals/bohomane_refonte/modules/amchoose")
OUT_DIR = Path(__file__).resolve().parents[1] / "exports" / "amchoose-product"
STAGING_DIR = OUT_DIR / "_staging" / "amchoose"
MODULE_NAME = "amchoose"
VERSION = "4.3.1"

EXCLUDE_DIR_NAMES = {".git", "__MACOSX", ".cursor"}
EXCLUDE_FILE_NAMES = {
    ".DS_Store",
    ".gitignore",
    "config_fr.xml",
    "error_log",
    "rand.php",
    ".php-cs-fixer.dist.php",
    ".php-cs-fixer.cache",
}
EXCLUDE_SUFFIXES = {".csv", ".txt", ".log"}
EXCLUDE_LOG_DIR_CONTENT = True


def should_include(path: Path) -> bool:
    rel = path.relative_to(MODULE_SRC)
    for part in rel.parts:
        if part in EXCLUDE_DIR_NAMES:
            return False
    if path.name in EXCLUDE_FILE_NAMES:
        return False
    if path.suffix.lower() in EXCLUDE_SUFFIXES:
        return False
    if EXCLUDE_LOG_DIR_CONTENT and "log" in rel.parts and path.name != "index.php":
        return False
    return True


def stage_module() -> Path:
    if STAGING_DIR.exists():
        shutil.rmtree(STAGING_DIR.parent)
    STAGING_DIR.mkdir(parents=True)

    for path in sorted(MODULE_SRC.rglob("*")):
        if not path.is_file() or not should_include(path):
            continue
        rel = path.relative_to(MODULE_SRC)
        dest = STAGING_DIR / rel
        dest.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(path, dest)

    for subdir in ("log", "export", "import"):
        target = STAGING_DIR / subdir
        target.mkdir(parents=True, exist_ok=True)
        index_src = MODULE_SRC / subdir / "index.php"
        if index_src.is_file():
            shutil.copy2(index_src, target / "index.php")

    return STAGING_DIR


def create_zip(staging: Path) -> Path:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    zip_path = OUT_DIR / f"{MODULE_NAME}-{VERSION}.zip"
    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
        for path in sorted(staging.rglob("*")):
            if not path.is_file():
                continue
            arcname = f"{MODULE_NAME}/{path.relative_to(staging).as_posix()}"
            zf.write(path, arcname)
    return zip_path


def main() -> None:
    staging = stage_module()
    zip_path = create_zip(staging)
    shutil.rmtree(staging.parent)
    size_kb = zip_path.stat().st_size // 1024
    print(f"Archive : {zip_path}")
    print(f"Taille  : {size_kb} Ko")


if __name__ == "__main__":
    main()
