#!/usr/bin/env python3
"""Met à jour la fiche produit WooCommerce Pennylane (ZIP téléchargeable + métadonnées)."""

from __future__ import annotations

import json
import sys
import uuid
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))

from article_studio.config import load_config
from article_studio.wp_client import _request, upload_media

ASSETS = ROOT / "exports" / "pennylane-product"
VERSION = "1.2.9"
ZIP_PATH = ASSETS / f"pennylane-{VERSION}.zip"
PRODUCT_ID = 16010
SLUG = "module-prestashop-pennylane-synchronisation"
SKU = f"pennylane-{VERSION}"
DOWNLOAD_NAME = f"module-synchronisation-pennylane-prestashop-{VERSION}"

CHANGELOG_ENTRY = (
    f"<h3>Version {VERSION} — 10/09/2026</h3><ul>"
    "<li>La licence reste reconnue après l'enregistrement de la configuration (cache positif conservé, appels API plus robustes)</li>"
    "<li>Correction de la détection du domaine boutique en HTTPS</li></ul>"
)


def get_json(base_url: str, user: str, password: str, path: str) -> dict | list:
    url = f"{base_url.rstrip('/')}{path}"
    _, data = _request("GET", url, user, password)
    return data


def put_json(base_url: str, user: str, password: str, path: str, payload: dict) -> dict:
    url = f"{base_url.rstrip('/')}{path}"
    _, data = _request(
        "PUT",
        url,
        user,
        password,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )
    return data


def find_product_id(base: str, user: str, pwd: str) -> int:
    data = get_json(base, user, pwd, f"/wp-json/wc/v3/products?slug={SLUG}&per_page=1")
    if not isinstance(data, list) or not data:
        raise RuntimeError(f"Produit introuvable (slug={SLUG})")
    return int(data[0]["id"])


def main() -> int:
    if not ZIP_PATH.is_file():
        raise FileNotFoundError(f"Archive introuvable : {ZIP_PATH}")

    cfg = load_config()
    base = cfg.wp_base_url
    user = cfg.wp_user
    pwd = cfg.wp_application_password.replace(" ", "")

    product_id = PRODUCT_ID
    product = get_json(base, user, pwd, f"/wp-json/wc/v3/products/{product_id}")
    if not isinstance(product, dict):
        raise RuntimeError("Réponse produit invalide")

    print(f"Produit #{product_id} — upload ZIP…")
    zip_media = upload_media(
        base,
        user,
        pwd,
        ZIP_PATH,
        alt_text=f"Module PrestaShop synchronisation Pennylane v{VERSION}",
        title=DOWNLOAD_NAME,
    )
    zip_url = zip_media.get("source_url") or zip_media.get("guid", {}).get("rendered", "")
    downloads = [
        {
            "id": "pennylane-dl",
            "name": DOWNLOAD_NAME,
            "file": zip_url,
        }
    ]
    print(f"  ZIP : {zip_url}")

    meta = {m["key"]: m.get("value") for m in product.get("meta_data", []) if isinstance(m, dict)}
    changelog = (meta.get("changelog") or "").strip()
    if CHANGELOG_ENTRY not in changelog:
        changelog = CHANGELOG_ENTRY + changelog

    put_json(
        base,
        user,
        pwd,
        f"/wp-json/wc/v3/products/{product_id}",
        {
            "sku": SKU,
            "downloads": downloads,
            "meta_data": [
                {"key": "derniere_mise_a_jour", "value": "20260910"},
                {"key": "version_du_module__theme", "value": "V1.2.9"},
                {"key": "changelog", "value": changelog},
            ],
        },
    )

    variations = get_json(base, user, pwd, f"/wp-json/wc/v3/products/{product_id}/variations?per_page=100")
    if isinstance(variations, list):
        for var in variations:
            vid = int(var["id"])
            put_json(
                base,
                user,
                pwd,
                f"/wp-json/wc/v3/products/{product_id}/variations/{vid}",
                {"downloadable": True, "downloads": downloads},
            )
            print(f"  variation #{vid} mise à jour")

    print(f"\nFiche produit mise à jour : {base}/produit/{SLUG}/")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
