#!/usr/bin/env python3
"""
RMG.uz sayfasindaki marka logolarini (t396 / tildacdn) bulup assets/svg/trust/ 
klasorune indirir. Kullanim: python scripts/fetch_rmg_logos.py
Gereksinim: pip install requests
"""
import re
import os
import sys
from pathlib import Path
from urllib.request import urlopen, Request
from urllib.parse import urljoin

URL = "https://www.rmg.uz/"
OUT_DIR = Path(__file__).resolve().parent.parent / "assets" / "images" / "trust"
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}

def main():
    print("Fetching", URL, "...")
    try:
        req = Request(URL, headers=HEADERS)
        with urlopen(req, timeout=25) as r:
            html = r.read().decode("utf-8", errors="ignore")
    except Exception as e:
        print("Hata:", e)
        sys.exit(1)

    # Tilda / tildacdn image URL'leri (static, thumb, vb.)
    patterns = [
        r'https://static\.tildacdn\.(?:com|net|info|pro)/[^"\'\s<>]+\.(?:png|jpg|jpeg|svg|webp)',
        r'https://thumb\.tildacdn\.(?:com|net)/[^"\'\s<>]+',
        r'data-src="(https://[^"]+tildacdn[^"]+)"',
        r'url\(["\']?(https://[^"\')\s]+tildacdn[^"\')\s]+)["\']?\)',
    ]
    seen = set()
    urls = []
    for p in patterns:
        for m in re.finditer(p, html, re.I):
            u = m.group(1) if m.lastindex else m.group(0)
            u = u.split("?")[0].strip("'\")")
            if u and u not in seen and "tildacdn" in u:
                seen.add(u)
                urls.append(u)

    # t396 ile gecen bloklardaki img src
    for m in re.finditer(r'src=["\'](https://[^"\']+)["\']', html):
        u = m.group(1)
        if "tildacdn" in u or "t396" in html[max(0, m.start()-500):m.start()]:
            if u not in seen:
                seen.add(u)
                urls.append(u)

    if not urls:
        print("HTML icinde tildacdn logo URL'si bulunamadi. Sayfa JS ile yukleniyor olabilir.")
        print("Alternatif: https://www.rmg.uz/ adresini tarayicida acin, marka logolarinin oldugu")
        print("  alanda her logoya sag tiklayip 'Resmi farkli kaydet' ile assets/images/trust/ klasorune kaydedin.")
        sys.exit(0)

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    print(f"Bulunan {len(urls)} URL, indiriliyor...")
    for i, u in enumerate(urls[:15]):  # en fazla 15 logo
        try:
            r = urlopen(Request(u, headers=HEADERS), timeout=15)
            ext = Path(u).suffix or ".png"
            if "format" in u or "resize" in u:
                ext = ".png"
            path = OUT_DIR / f"rmg_logo_{i+1}{ext}"
            path.write_bytes(r.read())
            print("  ", path.name)
        except Exception as e:
            print("  Atlandi:", u[:60], "...", e)
    print("Tamamlandi:", OUT_DIR)

if __name__ == "__main__":
    main()
