#!/usr/bin/env python3
"""Собирает categories.json для pred-prod из меню WooCommerce."""
from __future__ import annotations

import json
import sys
from pathlib import Path
from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup

ROOT = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
sys.path.insert(0, str(ROOT / "ivk"))
from pred_prod_settings import BASE_URL, HTTP_AUTH, PER_PAGE  # noqa: E402

SEED_PAGES = [
    f"{BASE_URL}/",
    f"{BASE_URL}/shop/",
]


def fetch(url: str) -> BeautifulSoup:
    kwargs = {"timeout": 60}
    if HTTP_AUTH:
        kwargs["auth"] = HTTP_AUTH
    response = requests.get(url, **kwargs)
    response.raise_for_status()
    return BeautifulSoup(response.text, "html.parser")


def pages_for_category(category_url: str) -> int:
    soup = fetch(category_url)
    count = len(soup.select(".product-card"))
    if count >= PER_PAGE:
        return 15
    return max(1, (count + PER_PAGE - 1) // PER_PAGE)


def main() -> None:
    urls: dict[str, str] = {}
    for page in SEED_PAGES:
        soup = fetch(page)
        for link in soup.select('a[href]'):
            href = link.get("href", "")
            name = link.get_text(strip=True)
            if not name or not href:
                continue
            if "product_cat=" not in href and "/product-category/" not in href:
                continue
            if href.rstrip("/") in (f"{BASE_URL}/shop", f"{BASE_URL.rstrip('/')}/shop"):
                continue
            full = urljoin(BASE_URL + "/", href).split("&paged=")[0].split("#")[0]
            full = full.rstrip("/") + "/" if "/product-category/" in full else full
            urls[full] = name

    categories = []
    for url in sorted(urls, key=lambda u: urls[u].lower()):
        name = urls[url]
        page_limit = pages_for_category(url)
        categories.append(
            {
                "Название категории": name,
                "URL категории": url,
                "Количество страниц в категории": page_limit,
            }
        )

    out = ROOT / "ivk/categories.json"
    out.write_text(json.dumps(categories, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"wrote {len(categories)} categories to {out}")


if __name__ == "__main__":
    main()