#!/usr/bin/env python3
import hashlib
import re
import shutil
import xml.etree.ElementTree as ET
from collections import Counter
from pathlib import Path
from urllib.request import Request, urlopen

BASE = Path('/root/MARKETING_DAM')
UA = 'Mozilla/5.0'


def ensure(path: Path) -> Path:
    path.mkdir(parents=True, exist_ok=True)
    return path


def slugify(value: str) -> str:
    value = value.strip().replace(' ', '_')
    value = re.sub(r'[^A-Za-z0-9._-]+', '_', value)
    value = re.sub(r'_+', '_', value)
    return value.strip('_') or 'UNNAMED'


def copy_unique(src: Path, dest_dir: Path, rename_to: str | None = None) -> Path:
    ensure(dest_dir)
    name = rename_to or src.name
    dest = dest_dir / name
    if dest.exists():
        if dest.stat().st_size == src.stat().st_size:
            return dest
        digest = hashlib.sha1(str(src).encode('utf-8')).hexdigest()[:8]
        dest = dest_dir / f'{dest.stem}_{digest}{dest.suffix}'
    shutil.copy2(src, dest)
    return dest


def write_text(path: Path, text: str) -> None:
    ensure(path.parent)
    path.write_text(text.strip() + '\n', encoding='utf-8')


def fetch_el_corral_category_map() -> dict[str, str]:
    sitemap = 'https://www.elcorral.com/sitemap.xml'
    req = Request(sitemap, headers={'User-Agent': UA})
    with urlopen(req, timeout=30) as resp:
        root = ET.fromstring(resp.read())
    ns = {'sm': 'http://www.sitemaps.org/schemas/sitemap/0.9'}
    mapping = {}
    for node in root.findall('sm:url', ns):
        loc = node.find('sm:loc', ns)
        if loc is None or not loc.text:
            continue
        match = re.search(r'/categories/([0-9a-f-]{36})/([a-z0-9-]+)$', loc.text)
        if match:
            mapping[match.group(1)] = match.group(2)
    return mapping


def organize_el_corral() -> dict:
    src_root = BASE / 'INBOX' / 'WEBSITE_IMPORTS' / 'EL_CORRAL' / 'assets'
    brand_root = BASE / 'BRANDS' / 'EL_CORRAL' / 'WEBSITE_IMPORTED'
    product_root = BASE / 'PRODUCTS' / 'BRANDS' / 'EL_CORRAL' / 'WEBSITE_IMPORTED'
    category_root = product_root / 'CATEGORY_IMAGES'

    shutil.rmtree(category_root, ignore_errors=True)
    counts = Counter()
    category_slug_map = fetch_el_corral_category_map()

    for src in (src_root / 'd7364jmfys2bj.cloudfront.net' / 'categories').rglob('*.webp'):
        uuid = src.stem
        slug = category_slug_map.get(uuid, uuid)
        dest_dir = category_root / slugify(slug)
        rename = f'{slugify(slug)}_{uuid}.webp'
        copy_unique(src, dest_dir, rename)
        counts['category_images'] += 1

    product_images_dir = product_root / 'UNCLASSIFIED_PRODUCT_IMAGES'
    ensure(product_images_dir)
    for src in (src_root / 'd7364jmfys2bj.cloudfront.net' / 'products').glob('*'):
        if src.is_file():
            copy_unique(src, product_images_dir)
            counts['product_images'] += 1

    fallback = src_root / 'www.elcorral.com' / 'assets' / 'images' / 'product-fallback.webp'
    if fallback.exists():
        copy_unique(fallback, product_images_dir)
        counts['fallback_images'] += 1

    sic = src_root / 'www.elcorral.com' / 'assets' / 'images' / 'sic.png'
    if sic.exists():
        copy_unique(sic, brand_root / 'LEGAL_AND_COMPLIANCE')
        counts['brand_compliance_assets'] += 1

    write_text(
        product_root / 'README.txt',
        f'''EL_CORRAL website import organization

Source: /root/MARKETING_DAM/INBOX/WEBSITE_IMPORTS/EL_CORRAL

What was organized:
- Category images copied into CATEGORY_IMAGES/<category-slug>/ using the public sitemap mapping.
- Product images copied into UNCLASSIFIED_PRODUCT_IMAGES/.
- Public site data did not expose a clean product-to-image mapping, so product shots remain unclassified for now.

Counts:
- category_images: {counts['category_images']}
- product_images: {counts['product_images']}
- fallback_images: {counts['fallback_images']}
'''
    )

    write_text(
        brand_root / 'README.txt',
        f'''EL_CORRAL brand-level website import notes

Source: /root/MARKETING_DAM/INBOX/WEBSITE_IMPORTS/EL_CORRAL

Organized here:
- legal/compliance graphics such as SIC assets

Counts:
- brand_compliance_assets: {counts['brand_compliance_assets']}
'''
    )

    return dict(counts)


def classify_gourmet_upload(name: str) -> tuple[str, str]:
    n = name.lower()

    if name.endswith('.pdf'):
        if 'politica' in n or 'tratamiento_de_datos' in n:
            return ('brand_docs', 'LEGAL')
        if 'cronograma' in n or 'festival' in n:
            return ('brand_campaign_docs', 'CAMPAIGN_DOCUMENTS')
        if 'carta' in n or 'menu' in n or 'hh_' in n or 'cartahh' in n or 'brunch' in n:
            return ('brand_menu_docs', 'MENUS')
        return ('brand_docs', 'UNCLASSIFIED_DOCS')

    brand_keywords = [
        'banner', 'slide_', 'bodegon', 'miniaturas-web', 'bono-banner',
        'happy_hour', 'desayunos', 'background-container', 'image_7',
        'image_23', 'second_image_contact', 'sostenibilidad', 'cadena-de-valor',
        'whatsapp_image'
    ]
    if any(k in n for k in brand_keywords):
        if 'sostenibilidad' in n or 'cadena-de-valor' in n:
            return ('brand_sustainability', 'SUSTAINABILITY')
        if 'contact' in n:
            return ('brand_contact', 'CONTACT')
        return ('brand_campaigns', 'CAMPAIGNS')

    if n.startswith('ham_') or n.startswith('h_') or 'todoterreno' in n or 'doble_doble' in n or 'sweet_onion_bacon' in n or 'guacamole' in n or 'queso_azul' in n or 'gaucha' in n or 'portuguesa' in n or 'portobelo' in n:
        return ('product_hamburgers', 'HAMBURGERS')
    if 'big_dog' in n:
        return ('product_hot_dogs', 'HOT_DOGS')
    if 'ensalada' in n or 'salad' in n or 'coleslaw' in n:
        return ('product_salads', 'SALADS')
    if 'sopa' in n or 'crema_' in n:
        return ('product_soups', 'SOUPS')
    if 'torta' in n or 'pavlova' in n or 'heladito' in n:
        return ('product_desserts', 'DESSERTS')
    if 'smoothie' in n or 'jugos' in n or 'americano' in n or 'latte' in n or 'manhattan' in n or 'cafe' in n:
        return ('product_beverages', 'BEVERAGES')
    if 'calentao' in n or 'brunch' in n:
        return ('product_brunch', 'BRUNCH_BREAKFAST')
    if 'nachos' in n or 'casquitos' in n or 'anillos' in n or 'croquetas' in n or 'falafel' in n or 'corralitas' in n or 'acompa' in n or 'taco_taco' in n or 'portobelos_gratinados' in n:
        return ('product_starters_sides', 'STARTERS_SIDES')
    if n.endswith(('.jpg', '.jpeg', '.png', '.webp')):
        return ('product_unclassified', 'UNCLASSIFIED')
    return ('other', 'MISC')


def gourmet_unclassified_dir(name: str, product_root: Path) -> Path:
    n = name.lower()
    prefix_match = re.match(r'^(sp|tp|pc|gs|sf|sr|sa|ct|f|116)[-_]', n)
    if prefix_match:
        return product_root / 'UNCLASSIFIED' / f'CODED_{prefix_match.group(1).upper()}'
    if 'especialidades' in n or 'acompa' in n:
        return product_root / 'UNCLASSIFIED' / 'FAMILY_LABELS'
    return product_root / 'UNCLASSIFIED' / 'MISC_NAMED'


def organize_el_corral_gourmet() -> dict:
    src_assets = BASE / 'INBOX' / 'WEBSITE_IMPORTS' / 'EL_CORRAL_GOURMET' / 'assets'
    uploads = src_assets / 'www.elcorralgourmet.com' / 'static' / 'uploads'
    static_images = src_assets / 'www.elcorralgourmet.com' / 'static' / 'images'
    frontend_images = src_assets / 'www.elcorralgourmet.com' / 'static' / 'frontend' / 'images'

    brand_root = BASE / 'BRANDS' / 'EL_CORRAL_GOURMET'
    brand_imported = brand_root / 'WEBSITE_IMPORTED'
    campaigns_root = brand_root / 'CAMPAIGNS' / 'WEBSITE_IMPORTED'
    docs_root = brand_root / 'DOCUMENTS'
    product_root = BASE / 'PRODUCTS' / 'BRANDS' / 'EL_CORRAL_GOURMET' / 'WEBSITE_IMPORTED'
    fonts_root = BASE / 'FONTS' / 'BRANDS' / 'EL_CORRAL_GOURMET' / 'WEB_IMPORTED'

    shutil.rmtree(product_root / 'UNCLASSIFIED', ignore_errors=True)
    counts = Counter()

    for src in uploads.glob('*'):
        if not src.is_file():
            continue
        bucket, folder = classify_gourmet_upload(src.name)
        if bucket == 'brand_docs':
            copy_unique(src, docs_root / folder)
        elif bucket == 'brand_campaign_docs':
            copy_unique(src, campaigns_root / folder)
        elif bucket == 'brand_menu_docs':
            copy_unique(src, docs_root / folder)
        elif bucket == 'brand_campaigns':
            copy_unique(src, campaigns_root / 'BANNERS')
        elif bucket == 'brand_sustainability':
            copy_unique(src, docs_root / folder)
        elif bucket == 'brand_contact':
            copy_unique(src, brand_imported / folder)
        elif bucket == 'product_unclassified':
            copy_unique(src, gourmet_unclassified_dir(src.name, product_root))
        elif bucket.startswith('product_'):
            copy_unique(src, product_root / folder)
        else:
            copy_unique(src, brand_imported / 'MISC')
        counts[bucket] += 1

    for src in static_images.glob('*'):
        if src.is_file():
            copy_unique(src, brand_imported / 'ICONS_AND_MARKS')
            counts['brand_icons_and_marks'] += 1

    for src in frontend_images.glob('*'):
        if src.is_file():
            copy_unique(src, brand_imported / 'ICONS_AND_MARKS')
            counts['brand_icons_and_marks'] += 1

    write_text(
        product_root / 'README.txt',
        f'''EL_CORRAL_GOURMET website import organization

Source: /root/MARKETING_DAM/INBOX/WEBSITE_IMPORTS/EL_CORRAL_GOURMET

This branch contains product and menu imagery copied from the raw website import.
Family folders were assigned by filename heuristics. Files that could not be identified confidently were grouped under UNCLASSIFIED/, with coded sets split by filename prefix for easier review.

Counts:
- hamburgers: {counts['product_hamburgers']}
- hot_dogs: {counts['product_hot_dogs']}
- salads: {counts['product_salads']}
- soups: {counts['product_soups']}
- desserts: {counts['product_desserts']}
- beverages: {counts['product_beverages']}
- brunch_breakfast: {counts['product_brunch']}
- starters_sides: {counts['product_starters_sides']}
- unclassified: {counts['product_unclassified']}
'''
    )

    write_text(
        brand_imported / 'README.txt',
        f'''EL_CORRAL_GOURMET brand-level website import organization

Source: /root/MARKETING_DAM/INBOX/WEBSITE_IMPORTS/EL_CORRAL_GOURMET

Organized here:
- website icons and marks
- campaign banners and supporting images
- contact/supporting brand imagery
- sustainability visuals
- menu and legal documents

Counts:
- campaigns: {counts['brand_campaigns']}
- campaign_docs: {counts['brand_campaign_docs']}
- menu_docs: {counts['brand_menu_docs']}
- legal_docs: {counts['brand_docs']}
- sustainability_assets: {counts['brand_sustainability']}
- contact_assets: {counts['brand_contact']}
- icons_and_marks: {counts['brand_icons_and_marks']}
'''
    )

    write_text(
        fonts_root / 'README.txt',
        'No webfonts were detected during the EL_CORRAL_GOURMET website crawl on 2026-05-08.'
    )

    return dict(counts)


def main() -> None:
    ec = organize_el_corral()
    ecg = organize_el_corral_gourmet()
    print('EL_CORRAL', ec)
    print('EL_CORRAL_GOURMET', ecg)


if __name__ == '__main__':
    main()
