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

from __future__ import annotations

import shutil
import subprocess
import sys
import zipfile
from pathlib import Path

MODULE_SRC = Path(__file__).resolve().parents[1] / "exports" / "pennylane-product" / "pennylane"
OUT_DIR = Path(__file__).resolve().parents[1] / "exports" / "pennylane-product"
STAGING_DIR = OUT_DIR / "_staging" / "pennylane"
MODULE_NAME = "pennylane"
VERSION = "1.2.9"

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"}


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
    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)

    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 sync_amlicence_client() -> None:
    script = Path(__file__).resolve().parents[0] / "generate_amlicence_client.py"
    subprocess.run([sys.executable, str(script), "pennylane"], check=True)


def main() -> None:
    sync_amlicence_client()
    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()
