import csv
import re
import html
import xml.etree.ElementTree as ET
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit


INPUT_XML = Path(r"D:\Letöltések D meghajtó\1 PROJEKT\UNASAP_ES_MAKE\Több sheetet is meg lehet adni másolata\feed_sync\google_product_feed_20260612-072556.xml")
OUTPUT_DIR = Path(r"D:\Letöltések D meghajtó\1 PROJEKT\UNASAP_ES_MAKE\Több sheetet is meg lehet adni másolata\feed_sync\output")
CHUNK_SIZE = 5000
EMPTY_VALUE = "NINCS ADAT!"

NS = {"g": "http://base.google.com/ns/1.0"}

COLUMNS = [
    "id",
    "title",
    "description",
    "product_type",
    "link",
    "availability",
    "price",
    "sale_price",
    "brand",
    "custom_label_0",
    "custom_label_1",
    "custom_label_2",
]


def clean_text(value) -> str:
    return (value or "").strip()


def find_text(item, tag: str, namespace=None) -> str:
    if namespace:
        return clean_text(item.findtext(tag, default="", namespaces=namespace))
    return clean_text(item.findtext(tag, default=""))


def strip_url_params(url: str) -> str:
    url = clean_text(url)
    if not url:
        return ""

    parts = urlsplit(url)
    return urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))


def strip_html(value: str) -> str:
    value = clean_text(value)

    if not value:
        return ""

    value = html.unescape(value)
    value = re.sub(r"<script.*?>.*?</script>", " ", value, flags=re.I | re.S)
    value = re.sub(r"<style.*?>.*?</style>", " ", value, flags=re.I | re.S)
    value = re.sub(r"<[^>]+>", " ", value)
    value = html.unescape(value)
    value = re.sub(r"\s+", " ", value).strip()

    return value


def normalize(value: str) -> str:
    value = clean_text(value)

    if not value:
        return EMPTY_VALUE

    return value


def extract_item(item) -> dict:
    description = strip_html(find_text(item, "g:description", NS))

    return {
        "id": find_text(item, "g:id", NS),
        "title": find_text(item, "title"),
        "description": description,
        "product_type": find_text(item, "g:product_type", NS),
        "link": strip_url_params(find_text(item, "link")),
        "availability": find_text(item, "g:availability", NS),
        "price": find_text(item, "g:price", NS),
        "sale_price": find_text(item, "g:sale_price", NS),
        "brand": find_text(item, "g:brand", NS),
        "custom_label_0": find_text(item, "g:custom_label_0", NS),
        "custom_label_1": find_text(item, "g:custom_label_1", NS),
        "custom_label_2": find_text(item, "g:custom_label_2", NS),
    }


def write_chunk(rows: list[dict], chunk_index: int):
    output_path = OUTPUT_DIR / f"timar_{chunk_index:03d}.csv"

    with open(output_path, "w", encoding="utf-8-sig", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=COLUMNS)
        writer.writeheader()

        for row in rows:
            writer.writerow({col: normalize(row.get(col, "")) for col in COLUMNS})

    print(f"Kész: {output_path} | sorok: {len(rows)}")


def main():
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    rows = []
    chunk_index = 1
    total = 0
    skipped = 0

    for event, elem in ET.iterparse(INPUT_XML, events=("end",)):
        tag = elem.tag.split("}")[-1]

        if tag != "item":
            continue

        product = extract_item(elem)

        if product.get("availability", "").strip().lower() != "in_stock":
            skipped += 1
            elem.clear()
            continue

        rows.append(product)
        total += 1

        if len(rows) >= CHUNK_SIZE:
            write_chunk(rows, chunk_index)
            chunk_index += 1
            rows = []

        elem.clear()

    if rows:
        write_chunk(rows, chunk_index)

    print("==== KÉSZ ====")
    print(f"Exportált termékek: {total}")
    print(f"Kihagyva availability miatt: {skipped}")
    print(f"Chunk méret: {CHUNK_SIZE}")


if __name__ == "__main__":
    main()