#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
crawl_and_sync_fins.py
1. Harvests existing deactivated fin rows from surfboards_db.boards.
2. Crawls Shopify UCP fin catalogs across REAL Watersports (#21), Hawaiian South Shore (#22),
   Cleanline Surf (#23), The Surf Station (#24), Hansen Surfboards (#27), Rider Shack (#28),
   Mollusk (#31), Bing (#32), Album (#33), CLIPS HAWAII (#34), Sharp Eye JP (#35), Degree 33 (#36),
   Hobie (#37), Firewire (#40), Channel Islands (#41), Pyzel (#42), JS (#44), Thomas (#47),
   Christenson (#50), DHD (#55), Quality Hawaii (#57), Thalia Surf (#59),
   plus official fin stores (#64 FCS, #65 Futures, #66 True Ames, #67 Captain Fin, #68 NVS, #69 Flying Diamonds, #70 Deflow).
3. Crawls Luvsurf (#5) fin categories (FCS II / Futures).
4. Builds learned_fin_sku_consensus.json (`{maker}|{clean_sku}`) and fin_spec_catalog.json,
   and re-normalizes 100% of fins.
"""
import hashlib
import json
import re
import ssl
import sys
import time
import urllib.request
from collections import Counter, defaultdict
from pathlib import Path
from bs4 import BeautifulSoup
import pymysql

sys.path.insert(0, "/var/www/board-search/scraper")
sys.path.insert(0, "/var/www/board-search/fin/scraper")
import db_upsert
import shopify_board_ucp
from fin_normalizer import FinNormalizer

conn = db_upsert.get_connection()
fx_map = db_upsert.sync_daily_fx_rates(conn)
norm = FinNormalizer("/var/www/board-search/fin/fin_master.json")

with conn.cursor() as cur:
    cur.execute("SELECT id, site_key, name, is_overseas, base_currency, default_shipping_jpy FROM shops")
    SHOPS_BY_ID = {int(r["id"]): r for r in cur.fetchall()}


def upsert_fin_row(cur, shop_id: int, item: dict) -> bool:
    shop = SHOPS_BY_ID.get(shop_id) or {"is_overseas": 1, "base_currency": "USD", "default_shipping_jpy": 4500}
    raw_title = str(item.get("title") or "").strip()
    raw_desc = str(item.get("description") or "").strip()
    source_url = str(item.get("source_url") or "").strip()
    if not raw_title or not source_url:
        return False

    orig_curr = str(item.get("original_currency") or shop.get("base_currency") or "JPY").upper()
    orig_price = float(item.get("original_price") or 0.0)
    base_jpy = int(item.get("base_price") or 0)
    fx_rate, _ = fx_map.get(orig_curr, (154.80 if orig_curr != "JPY" else 1.0, ""))

    if int(shop.get("is_overseas") or 0) == 1:
        if orig_curr == "JPY" or orig_price <= 0:
            orig_curr = str(shop.get("base_currency") or "USD").upper()
            fx_rate, _ = fx_map.get(orig_curr, (154.80, ""))
            if base_jpy > 0 and fx_rate > 0:
                orig_price = round(base_jpy / fx_rate, 2)
        if base_jpy <= 0 and orig_price > 0:
            base_jpy = int(round(orig_price * fx_rate))
        ship_jpy = 4500  # International small packet shipping for fins
    else:
        orig_curr = "JPY"
        orig_price = 0.0
        fx_rate = 1.0
        ship_jpy = 0 if base_jpy >= 11000 else 880

    if norm.is_non_fin_item(raw_title, raw_desc, price_jpy=base_jpy, source_url=source_url):
        return False

    res = norm.normalize({
        "title": raw_title,
        "title_en": item.get("title_en") or raw_title,
        "description": raw_desc,
        "vendor": item.get("vendor") or "",
        "model_code": item.get("model_code") or item.get("source_id") or "",
        "source_id": item.get("source_id") or "",
        "condition_type": item.get("condition_type") or "new",
    })

    imgs = item.get("image_urls")
    if isinstance(imgs, str):
        try:
            imgs = json.loads(imgs)
        except Exception:
            imgs = []
    if not isinstance(imgs, list):
        imgs = []
    main_img = str(item.get("main_image_url") or (imgs[0] if imgs else "/img/no-img.png")).strip()
    if not imgs and main_img and main_img != "/img/no-img.png":
        imgs = [main_img]
    if not main_img or main_img == "/img/no-img.png":
        return False

    total_jpy = base_jpy + ship_jpy if base_jpy > 0 else 0
    dedup_hash = hashlib.md5(source_url.encode("utf-8")).hexdigest()

    cur.execute("""
        INSERT INTO fins (
            shop_id, source_id, source_url,
            product_type, origin_type, maker, sub_maker, shaper,
            series_name, series_slug, model_name, model_slug,
            model_code, maker_sku_key,
            title, title_en, display_title,
            condition_type, condition_rank,
            fin_system, fin_setup, size_code, size_bucket, fin_inch, material,
            color, raw_color,
            base_price, total_price, original_currency, original_price, fx_rate, shipping_jpy, is_free_shipping,
            main_image_url, image_urls, description, dedup_hash, is_active, scraped_at
        ) VALUES (
            %s, %s, %s,
            %s, %s, %s, %s, %s,
            %s, %s, %s, %s,
            %s, %s,
            %s, %s, %s,
            %s, %s,
            %s, %s, %s, %s, %s, %s,
            %s, %s,
            %s, %s, %s, %s, %s, %s, %s,
            %s, %s, %s, %s, 1, NOW()
        )
        ON DUPLICATE KEY UPDATE
            product_type = VALUES(product_type),
            maker = VALUES(maker),
            sub_maker = VALUES(sub_maker),
            shaper = VALUES(shaper),
            series_name = VALUES(series_name),
            series_slug = VALUES(series_slug),
            model_name = VALUES(model_name),
            model_slug = VALUES(model_slug),
            model_code = VALUES(model_code),
            maker_sku_key = VALUES(maker_sku_key),
            title = VALUES(title),
            display_title = VALUES(display_title),
            condition_type = VALUES(condition_type),
            condition_rank = VALUES(condition_rank),
            fin_system = VALUES(fin_system),
            fin_setup = VALUES(fin_setup),
            size_code = VALUES(size_code),
            size_bucket = VALUES(size_bucket),
            fin_inch = VALUES(fin_inch),
            material = VALUES(material),
            color = VALUES(color),
            raw_color = VALUES(raw_color),
            base_price = VALUES(base_price),
            total_price = VALUES(total_price),
            original_currency = VALUES(original_currency),
            original_price = VALUES(original_price),
            fx_rate = VALUES(fx_rate),
            shipping_jpy = VALUES(shipping_jpy),
            main_image_url = VALUES(main_image_url),
            image_urls = VALUES(image_urls),
            is_active = 1,
            scraped_at = NOW()
    """, (
        shop_id, str(item.get("source_id") or res["model_code"])[:120], source_url[:500],
        res["product_type"], res["origin_type"], res["maker"], res["sub_maker"], res["shaper"],
        res["series_name"], res["series_slug"], res["model_name"], res["model_slug"],
        res["model_code"], res["maker_sku_key"],
        res["title"], res["title_en"], res["display_title"],
        res["condition_type"], res["condition_rank"],
        res["fin_system"], res["fin_setup"], res["size_code"], res["size_bucket"], res["fin_inch"], res["material"],
        res["color"], res["raw_color"],
        base_jpy, total_jpy, orig_curr, orig_price, fx_rate, ship_jpy, (1 if ship_jpy == 0 else 0),
        main_img[:500], json.dumps(imgs[:8], ensure_ascii=False), raw_desc[:2500], dedup_hash,
    ))
    return True


# 1. Harvest existing fin rows from boards (is_active=0)
with conn.cursor() as cur:
    cur.execute("SELECT * FROM boards WHERE is_active = 0")
    inactive_boards = cur.fetchall()
    harvested = 0
    for r in inactive_boards:
        if upsert_fin_row(cur, int(r["shop_id"]), r):
            harvested += 1
    conn.commit()
    print(f"[Step 1] Harvested {harvested} fins from existing boards table.", flush=True)

# 2. Crawl Shopify UCP fin catalogs across multi-brand and official fin stores
FIN_SHOPIFY_SHOPS = [
    (64, "www.surffcs.com",               ["FCS II", "Keel", "Longboard Fin", "Al Merrick", "Mayhem", "Machado"], 4, "USD", "US"),
    (65, "futuresfins.com",               ["Thruster", "Twin", "Quad", "Longboard", "Alpha", "Blackstix"], 4, "USD", "US"),
    (66, "www.trueames.com",              ["Greenough", "Skip Frye", "Twin", "Keel", "Single Fin", "Bonzer"], 4, "USD", "US"),
    (67, "captainfin.com",                ["Surf Fins", "Christenson", "Tyler Warren", "Single Fin", "Twin Fin", "Quad"], 4, "USD", "US"),
    (68, "www.surfnvs.com",               ["Apex", "Twin", "Quad", "Thruster", "Album", "Kraken"], 3, "USD", "US"),
    (69, "flyingdiamondsofcalifornia.com",["CJ Nelson", "Kai Sallas", "Single Fin", "Longboard Fin"], 3, "USD", "US"),
    (70, "deflowsurf.com",                ["Fin", "Twin", "Keel", "Single", "Thruster"], 3, "EUR", "ES"),
    (21, "www.realwatersports.com",       ["Surfboard Fins", "FCS II", "Futures Fins", "True Ames", "Captain Fin"], 4, "USD", "US"),
    (22, "www.hawaiiansouthshore.com",    ["FCS II", "Futures Fins", "Single Fin", "Keel Fin"], 3, "USD", "US"),
    (23, "www.cleanlinesurf.com",         ["Surfboard Fins", "FCS II", "Futures Fins", "Captain Fin", "True Ames"], 4, "USD", "US"),
    (24, "www.surfstationstore.com",      ["Surfboard Fins", "FCS II", "Futures Fins"], 4, "USD", "US"),
    (27, "www.hansensurf.com",            ["Surfboard Fins", "FCS II", "Futures Fins", "Captain Fin"], 3, "USD", "US"),
    (28, "www.ridershack.com",            ["Surfboard Fins", "FCS II", "Futures"], 3, "USD", "US"),
    (31, "mollusksurfshop.com",           ["Fins", "True Ames", "Captain Fin"], 2, "USD", "US"),
    (32, "bingsurf.com",                  ["Fin", "Single Fin", "Twin Fin"], 2, "USD", "US"),
    (33, "albumsurf.com",                 ["Fin", "Twin Fin", "Quad Fin", "NVS"], 2, "USD", "US"),
    (34, "clipshawaii.com",               ["FCS", "Futures", "Fin"], 2, "USD", "US"),
    (35, "sharpeyesurfboards.jp",         ["FCS", "Futures", "フィン"], 2, "JPY", "JP"),
    (37, "hobiesurfshop.com",             ["Fin", "Single Fin", "True Ames"], 2, "USD", "US"),
    (40, "www.firewiresurfboards.com",    ["Machado", "Endorfins", "Fins"], 2, "USD", "US"),
    (41, "cisurfboards.com",              ["Fins", "AM1", "AM2", "BMT", "Keel"], 2, "USD", "US"),
    (42, "www.pyzelsurfboards.com",       ["Fins", "JJF", "Futures", "FCS"], 2, "USD", "US"),
    (44, "us.jsindustries.com",           ["Fins", "Power Twin", "FCS", "Futures"], 2, "USD", "US"),
    (47, "thomassurfboards.com",          ["Fin", "Single Fin"], 2, "AUD", "AU"),
    (50, "christensonsurfboards.com",     ["Fin", "Keel", "Tracker"], 2, "USD", "US"),
    (55, "dhdsurf.com",                   ["Fins", "MF", "FCS", "Futures"], 2, "AUD", "AU"),
    (57, "www.qualitysurfboardshawaii.com",["Fins", "FCS", "Futures"], 2, "USD", "US"),
    (59, "www.thaliasurf.com",            ["Surf Fins", "Captain Fin", "True Ames", "Futures"], 3, "USD", "US"),
]

for shop_id, dom, queries, max_pg, curr, country in FIN_SHOPIFY_SHOPS:
    t0 = time.time()
    try:
        items = shopify_board_ucp.fetch_ucp_catalog(dom, queries=queries, max_pages_per_query=max_pg, currency=curr, country=country)
        added = 0
        with conn.cursor() as cur:
            for it in items:
                if upsert_fin_row(cur, shop_id, it):
                    added += 1
        conn.commit()
        print(f"[FIN UCP #{shop_id:2d} {dom:32s}] raw={len(items):4d} -> upserted={added:4d} ({time.time()-t0:.1f}s)", flush=True)
    except Exception as e:
        print(f"[FIN UCP ERR #{shop_id} {dom}] {e}", flush=True)

# 3. Build learned_fin_sku_consensus.json (`{maker}|{clean_sku}`) & fin_spec_catalog.json
with conn.cursor() as cur:
    cur.execute("""
        SELECT maker, model_code, model_slug, COUNT(*) as cnt
        FROM fins
        WHERE is_active = 1 AND model_slug != 'unclassified' AND model_code != ''
        GROUP BY maker, model_code, model_slug
        ORDER BY cnt DESC
    """)
    exact_map = {}
    prefix_votes = defaultdict(Counter)
    for r in cur.fetchall():
        mkr = r["maker"]
        sku = r["model_code"]
        slug = r["model_slug"]
        key = f"{mkr}|{sku}"
        if key not in exact_map:
            exact_map[key] = slug
        for plen in (9, 8, 7, 6):
            if len(sku) >= plen and not sku[:plen].isdigit():
                prefix_votes[f"{mkr}|{sku[:plen]}"][slug] += int(r["cnt"])

    prefix_map = {}
    for pk, cnts in prefix_votes.items():
        top_slug, top_c = cnts.most_common(1)[0]
        if top_c >= 2 and top_c / sum(cnts.values()) >= 0.85:
            prefix_map[pk] = top_slug

    sku_consensus = {"exact": exact_map, "prefix": prefix_map}
    for sp in [
        Path("/var/www/board-search/fin/scraper/learned_fin_sku_consensus.json"),
        Path("/var/www/board-search/fin/learned_fin_sku_consensus.json"),
    ]:
        with open(sp, "w", encoding="utf-8") as f:
            json.dump(sku_consensus, f, ensure_ascii=False, indent=2)

    cur.execute("SELECT COUNT(*) as total, SUM(CASE WHEN model_slug!='unclassified' THEN 1 ELSE 0 END) as matched, COUNT(DISTINCT shop_id) as shops, COUNT(DISTINCT maker_sku_key) as unique_skus FROM fins WHERE is_active = 1")
    st = cur.fetchone()
    print(f"=== FIN-SEARCH TOTAL ACTIVE FINS: {st['total']} (Catalog Matched: {st['matched']}, Unique Maker+SKU: {st['unique_skus']}, Active Shops: {st['shops']}) ===", flush=True)
