#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Superium — page builder
=======================

Generates every HTML page in the package from the shared chrome in
``layout.py``, the components in ``components.py`` and the page bodies in
``pages_*.py``, using the catalogue produced by ``fetch_products.py``.

    python tools/build_pages.py            # build everything
    python tools/build_pages.py home       # build only pages matching "home"

Also emits ``assets/data/products.js``, which assigns
``window.SUPERIUM_PRODUCTS``. It is a plain script rather than a fetch of the
JSON so the template still works when opened from ``file://``.

This is development tooling. The generated .html files are the product — a
buyer can edit them directly and never run this script.
"""

from __future__ import annotations

import json
import shutil
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

import pages_account  # noqa: E402
import pages_checkout  # noqa: E402
import pages_home  # noqa: E402
import pages_shop  # noqa: E402
from layout import page  # noqa: E402

ROOT = Path(__file__).resolve().parent.parent
DATA = ROOT / "assets" / "data"
BRAND_DIR = ROOT / "assets" / "images" / "brand"

HOME_CSS = ["superium-home.css"]
SHOP_CSS = ["superium-shop.css"]
FLOW_CSS = ["superium-shop.css", "superium-flow.css"]
# Leaflet powers the real maps on the checkout / address pages.
MAP_CSS = FLOW_CSS + ["vendor/leaflet/leaflet.css"]
MAP_JS = ["vendor/leaflet/leaflet.js"]
ACCOUNT_CSS = ["superium-account.css"]


# --------------------------------------------------------------------------
# Data
# --------------------------------------------------------------------------


def load_catalogue() -> tuple[list[dict], list[dict]]:
    path = DATA / "products.json"
    if not path.exists():
        sys.exit(
            "✗ assets/data/products.json not found.\n"
            "  Run: python tools/fetch_products.py --source art"
        )
    data = json.loads(path.read_text(encoding="utf-8"))
    return data["products"], data["categories"]


def write_products_js(payload_path: Path) -> None:
    data = json.loads(payload_path.read_text(encoding="utf-8"))
    js = (
        "/* Generated by tools/build_pages.py — do not edit by hand.\n"
        "   Assigns window.SUPERIUM_PRODUCTS so the pages work from file:// too. */\n"
        "window.SUPERIUM_PRODUCTS = "
        + json.dumps(
            {"categories": data["categories"], "products": data["products"]},
            ensure_ascii=False,
            separators=(",", ":"),
        )
        + ";\n"
    )
    (DATA / "products.js").write_text(js, encoding="utf-8")


# --------------------------------------------------------------------------
# Brand assets
# --------------------------------------------------------------------------

FAVICON = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
  <rect width="40" height="40" rx="9" fill="#F2600C"/>
  <path d="M8.5 14.5h23l-2.1 15a3 3 0 0 1-3 2.6H13.6a3 3 0 0 1-3-2.6z"
        stroke="#fff" stroke-width="2.4" stroke-linejoin="round" fill="none"/>
  <path d="M15 14.5c0-4.6 2.3-7.4 5-7.4s5 2.8 5 7.4"
        stroke="#fff" stroke-width="2.4" stroke-linecap="round" fill="none"/>
</svg>
"""


def write_brand_assets() -> None:
    BRAND_DIR.mkdir(parents=True, exist_ok=True)
    (BRAND_DIR / "favicon.svg").write_text(FAVICON, encoding="utf-8")


# --------------------------------------------------------------------------
# Page manifest
# --------------------------------------------------------------------------


def build_manifest(products: list[dict], categories: list[dict]) -> list[dict]:
    """
    One entry per output file. ``group`` and ``blurb`` are reused by
    build_demo.py to lay out the showcase, so the manifest is the single
    source of truth for "what pages exist".
    """
    return [
        # --- Homepages ---------------------------------------------------
        {
            "file": "home-1-fresh.html",
            "group": "homepages",
            "label": "خانه ۱ - تازه",
            "blurb": "پالت گرم، هیرو کلاژی، ریل دسته‌بندی گرد و فوتر کامل",
            "theme": "fresh",
            "title": "خرید آنلاین سوپرمارکت",
            "description": "خرید سوپرمارکتی فوری از فروشگاه‌های محلی با ارسال زیر ۴۵ دقیقه",
            "body": pages_home.home_fresh(products, categories),
            "css": HOME_CSS,
            "footer": "wide",
        },
        {
            "file": "home-2-aqua.html",
            "group": "homepages",
            "label": "خانه ۲ - آکوا",
            "blurb": "پالت سرد، هیرو دوستونه با کارت زمان تحویل، چیدمان بنتو",
            "theme": "aqua",
            "title": "سوپرمارکت آنلاین",
            "description": "همه خرید هفته در یک سفارش - مقایسه قیمت بین فروشگاه‌های اطراف",
            "body": pages_home.home_aqua(products, categories),
            "css": HOME_CSS,
            "footer": "compact",
        },
        {
            "file": "home-3-graphite.html",
            "group": "homepages",
            "label": "خانه ۳ - گرافیت",
            "blurb": "پالت تیره خنثی، هیرو بنری، کاشی تک‌رنگ و شبکه قیمت‌محور",
            "theme": "graphite",
            "title": "سوپرمارکت شبانه‌روزی",
            "description": "سفارش تا نیمه‌شب، تحویل زیر یک ساعت",
            "body": pages_home.home_graphite(products, categories),
            "css": HOME_CSS,
            "footer": "slim",
        },
        # --- Shop --------------------------------------------------------
        {
            "file": "market.html",
            "group": "shop",
            "label": "فروشگاه",
            "blurb": "لیست کالا با فیلتر، مرتب‌سازی، نمای شبکه/لیست و صفحه‌بندی",
            "title": "همه کالاها",
            "description": "خرید از میان صدها کالای سوپرمارکتی با فیلتر دسته، برند و قیمت",
            "body": pages_shop.market(products, categories),
            "css": SHOP_CSS,
            "js": ["superium-market.js"],
        },
        {
            "file": "product.html",
            "group": "shop",
            "label": "جزئیات کالا",
            "blurb": "گالری، جعبه خرید، فروشندگان دیگر، مشخصات و نظرات",
            "title": "جزئیات کالا",
            "description": "مشخصات، قیمت و فروشندگان این کالا",
            "body": pages_shop.product(products),
            "css": SHOP_CSS,
            "js": ["superium-product.js"],
        },
        {
            "file": "cart.html",
            "group": "shop",
            "label": "سبد خرید",
            "blurb": "اقلام سبد، تغییر تعداد و خلاصه چسبان فاکتور",
            "title": "سبد خرید",
            "description": "بررسی و ویرایش سبد خرید",
            "body": pages_shop.cart(),
            "css": SHOP_CSS,
        },
        {
            "file": "vendors.html",
            "group": "shop",
            "label": "مقایسه فروشگاه‌ها",
            "blurb": "قیمت سبد شما در فروشگاه‌های اطراف، با کالای ناموجود و جایگزین",
            "title": "انتخاب فروشگاه",
            "description": "قیمت سبد خرید شما در فروشگاه‌های اطراف",
            "body": pages_shop.vendors(products),
            "css": SHOP_CSS,
        },
        {
            "file": "store.html",
            "group": "shop",
            "label": "صفحه فروشگاه",
            "blurb": "ویترین یک سوپرمارکت با جستجوی داخلی و سبد کنار صفحه",
            "title": "سوپرمارکت لوکس جردن",
            "description": "ویترین فروشگاه و خرید مستقیم از قفسه‌ها",
            "body": pages_shop.store(products, categories),
            "css": SHOP_CSS,
        },
        # --- Checkout ----------------------------------------------------
        {
            "file": "checkout.html",
            "group": "checkout",
            "label": "تسویه حساب",
            "blurb": "ارسال با پیک یا دریافت حضوری، زمان آماده‌سازی، کد تخفیف و درگاه",
            "title": "بررسی نهایی و پرداخت",
            "description": "انتخاب شیوه تحویل، زمان و پرداخت",
            "body": pages_checkout.checkout(),
            "css": MAP_CSS,
            "js": MAP_JS + ["superium-checkout.js", "superium-map.js"],
        },
        {
            "file": "address-map.html",
            "group": "checkout",
            "label": "انتخاب روی نقشه",
            "blurb": "انتخابگر نقشه با پین قابل جابه‌جایی - بدون SDK خارجی",
            "title": "انتخاب موقعیت روی نقشه",
            "description": "محل تحویل سفارش را روی نقشه مشخص کنید",
            "body": pages_checkout.address_map(),
            "css": MAP_CSS,
            "js": MAP_JS + ["superium-map.js"],
        },
        {
            "file": "address-add.html",
            "group": "checkout",
            "label": "افزودن آدرس",
            "blurb": "فرم آدرس با عنوان خانه/محل کار و موبایل تحویل‌گیرنده",
            "title": "افزودن آدرس جدید",
            "description": "ثبت نشانی و مشخصات تحویل‌گیرنده",
            "body": pages_checkout.address_add(),
            "css": MAP_CSS,
            "js": MAP_JS + ["superium-map.js"],
        },
        # --- Account -----------------------------------------------------
        {
            "file": "login.html",
            "group": "account",
            "label": "ورود",
            "blurb": "ورود با شماره موبایل و کد یک‌بارمصرف با شمارنده معکوس",
            "title": "ورود",
            "description": "ورود به حساب کاربری",
            "body": pages_account.login(),
            "css": ACCOUNT_CSS,
            "js": ["superium-auth.js"],
            "chrome": False,
        },
        {
            "file": "signup.html",
            "group": "account",
            "label": "ثبت‌نام",
            "blurb": "ساخت حساب: مشخصات، موبایل و پذیرش قوانین",
            "title": "ثبت‌نام",
            "description": "ساخت حساب کاربری جدید",
            "body": pages_account.signup(),
            "css": ACCOUNT_CSS,
            "js": ["superium-auth.js"],
            "chrome": False,
        },
        {
            "file": "profile.html",
            "group": "account",
            "label": "اطلاعات حساب",
            "blurb": "داشبورد کاربر: نام، نام خانوادگی، موبایل و آدرس پیش‌فرض",
            "title": "اطلاعات حساب",
            "description": "ویرایش اطلاعات حساب کاربری",
            "body": pages_account.profile(),
            "css": ACCOUNT_CSS,
        },
        {
            "file": "profile-orders.html",
            "group": "account",
            "label": "سفارش‌های من",
            "blurb": "تاریخچه سفارش با وضعیت جاری، تحویل‌شده و لغوشده",
            "title": "سفارش‌های من",
            "description": "پیگیری و تاریخچه سفارش‌ها",
            "body": pages_account.orders(),
            "css": ACCOUNT_CSS,
        },
        {
            "file": "profile-addresses.html",
            "group": "account",
            "label": "آدرس‌ها",
            "blurb": "مدیریت آدرس‌های ذخیره‌شده",
            "title": "آدرس‌های من",
            "description": "مدیریت آدرس‌های تحویل",
            "body": pages_account.addresses(),
            "css": ACCOUNT_CSS,
        },
        {
            "file": "support.html",
            "group": "account",
            "label": "پشتیبانی",
            "blurb": "پرسش‌های متداول آکاردئونی و فرم تماس",
            "title": "پشتیبانی و راهنما",
            "description": "پرسش‌های متداول و ارتباط با پشتیبانی",
            "body": pages_account.support(),
            "css": ACCOUNT_CSS,
        },
    ]


# --------------------------------------------------------------------------
# Build
# --------------------------------------------------------------------------

INDEX_REDIRECT = """<!doctype html>
<html lang="fa" dir="rtl">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="refresh" content="0; url=home-1-fresh.html" />
    <title>سوپردوپر مارکت</title>
    <link rel="canonical" href="home-1-fresh.html" />
  </head>
  <body>
    <p>در حال انتقال به <a href="home-1-fresh.html">صفحه اصلی</a> …</p>
  </body>
</html>
"""


def main() -> int:
    only = sys.argv[1] if len(sys.argv) > 1 else None

    products, categories = load_catalogue()
    write_products_js(DATA / "products.json")
    write_brand_assets()

    manifest = build_manifest(products, categories)
    written = 0

    for entry in manifest:
        if only and only not in entry["file"]:
            continue
        html = page(
            title=entry["title"],
            description=entry["description"],
            body=entry["body"],
            theme=entry.get("theme", "fresh"),
            footer_variant=entry.get("footer", "inner"),
            extra_css=entry.get("css"),
            extra_js=entry.get("js"),
            with_header=entry.get("chrome", True),
            with_footer=entry.get("chrome", True),
            with_fabs=entry.get("chrome", True),
        )
        (ROOT / entry["file"]).write_text(html, encoding="utf-8")
        written += 1
        print(f"  ✓ {entry['file']}")

    if not only:
        (ROOT / "index.html").write_text(INDEX_REDIRECT, encoding="utf-8")
        print("  ✓ index.html")
        # The manifest drives the showcase too.
        (DATA / "pages.json").write_text(
            json.dumps(
                [
                    {k: e[k] for k in ("file", "group", "label", "blurb")}
                    for e in manifest
                ],
                ensure_ascii=False,
                indent=2,
            ),
            encoding="utf-8",
        )

    print(f"\n{written} page(s) built.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
