#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
refine_fin_catalog.py
1. Expands fin_master.json with clean Japanese-normalized single models (zero slash bundling).
2. Purges non-fin noise (screws, plates, shims, Catch Surf Twig/Fat Bat/Skipper boards, pencils, etc.).
3. Re-normalizes all active fins with official_fin_shop_maker priority (#64->FCS, #65->フューチャー, #66->トゥルーアムス, #68->NVS, #70->デフロー, #41->チャネルアイランズ, #47->トーマスサーフボード).
4. Rebuilds learned_fin_sku_consensus.json (`{maker}|{clean_sku}`) and fin_spec_catalog.json.
"""
import json
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path
import pymysql

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

MASTER_PATH = Path("/var/www/board-search/fin/fin_master.json")
with open(MASTER_PATH, "r", encoding="utf-8") as f:
    master = json.load(f)

# Clean any slash in existing fin model names
for d in master["devices"]:
    d["model"] = d["model"].replace(" / ", "・").replace("/", "・")

EXTRA_FIN_MODELS = [
    # --- FCS ---
    {
        "maker": "FCS", "maker_slug": "fcs", "shaper": "Mason Ho (LOST)",
        "series": "メイヘム MB（全モデル）", "series_slug": "fcs-mayhem",
        "model": "メイソン・ホー MH PC AirCore", "slug": "fcs2-mason-ho",
        "product_type": "fcs2", "fin_setup": "トライ（3フィン）", "material": "AirCore（エアコア超軽量）", "default_size": "M",
        "aliases": ["FCS II Mason Ho", "Mason Ho PC AirCore", "FMHM-PC", "FMHL-PC"]
    },
    {
        "maker": "FCS", "maker_slug": "fcs", "shaper": "Nathan Florence / Gabe Medina",
        "series": "パフォーマー・リアクター・H4", "series_slug": "fcs-essentials",
        "model": "ガブリエル・メディーナ GM AirCore", "slug": "fcs2-gabe-medina",
        "product_type": "fcs2", "fin_setup": "トライ（3フィン）", "material": "AirCore（エアコア超軽量）", "default_size": "M",
        "aliases": ["FCS II GM", "Gabe Medina", "Gabriel Medina", "Yago Dora", "Sally Fitzgibbons", "Nathan Florence", "Hayden Shapes 3-Fin"]
    },
    {
        "maker": "FCS", "maker_slug": "fcs", "shaper": "FCS Longboard",
        "series": "パフォーマー・リアクター・H4", "series_slug": "fcs-essentials",
        "model": "フロー Flow ロングボード シングル", "slug": "fcs2-flow-single",
        "product_type": "single-box", "fin_setup": "シングル（1フィン）", "material": "PG / ファイバーグラス（ソリッド）", "default_size": "9.0\"",
        "aliases": ["FCS II Flow", "FCS Flow III", "Flow PG", "Flow Longboard"]
    },
    {
        "maker": "FCS", "maker_slug": "fcs", "shaper": "FCS Longboard",
        "series": "パフォーマー・リアクター・H4", "series_slug": "fcs-essentials",
        "model": "ピボット Pivot ロングボード シングル", "slug": "fcs2-pivot-single",
        "product_type": "single-box", "fin_setup": "シングル（1フィン）", "material": "PG / ファイバーグラス（ソリッド）", "default_size": "9.0\"",
        "aliases": ["FCS II Pivot", "FCS Pivot", "Pivot PG", "Pivot Single Fin", "Clique", "Fatboy", "Whip", " Hatchet"]
    },
    # --- フューチャー ---
    {
        "maker": "フューチャー", "maker_slug": "futures", "shaper": "Ethan Ewing / Pyzel",
        "series": "JJF・シグネチャー・ツイン", "series_slug": "futures-series",
        "model": "イーサン・ユーイング / パイゼル トライ", "slug": "futures-ethan-ewing",
        "product_type": "futures-plug", "fin_setup": "トライ（3フィン）", "material": "ハニカム（Honeycomb）", "default_size": "M",
        "aliases": ["Ethan Ewing", "Futures Pyzel", "Pyzel Thruster", "Pyzel Padillac", "Merrick x Dane", "Dane DD2"]
    },
    {
        "maker": "フューチャー", "maker_slug": "futures", "shaper": "Donald Takayama / Futures",
        "series": "JJF・シグネチャー・ツイン", "series_slug": "futures-series",
        "model": "サイドバイト SB1・ロングスタビ", "slug": "futures-side-bite",
        "product_type": "futures-plug", "fin_setup": "クアッドリア・サイド単品", "material": "ハニカム（Honeycomb）", "default_size": "S",
        "aliases": ["SIDE BITE", "サイドバイト", "SB1", "QD2", "Quad Rear"]
    },
    # --- NVS ---
    {
        "maker": "NVS", "maker_slug": "nvs", "shaper": "Stu Kenson / Rusty / Maurice Cole",
        "series": "アルバム・テイラーノックス・G10", "series_slug": "nvs-series",
        "model": "ストゥ・ケンソン・ラスティ ツインザー Apex G10", "slug": "nvs-stu-kenson-twinzer",
        "product_type": "futures-plug", "fin_setup": "クアッド（4フィン）", "material": "G10 グラス（Apex）", "default_size": "L",
        "aliases": ["Stu Kenson Twinzer", "Rusty Twinzer", "Rusty Twin", "Rusty Asym", "Maurice Cole Twinzer", "Maurice Cole Reverse", "David Vernor", "Grennan", "Hydroglass", "Mannkine", "Aipa Ahi", "Aipa Da Hook", "AM-Comp", "Kestrel", "C-Drive", "Indy Twinzer", "LARRY MABILE", "Dark Arts x NVS"]
    },
    # --- トゥルーアムス ---
    {
        "maker": "トゥルーアムス", "maker_slug": "true-ames", "shaper": "True Ames Fins",
        "series": "グリノー4A・スキップフライ・ラブレス", "series_slug": "true-ames-series",
        "model": "マンダラ・ラブレス ツインザー＆クアッド", "slug": "ta-mandala-twinzer",
        "product_type": "futures-plug", "fin_setup": "クアッド（4フィン）", "material": "PG / ファイバーグラス（ソリッド）", "default_size": "L",
        "aliases": ["Mandala Twinzer", "Lovelace Twinzer", "TA Twinzer", "True Ames Thruster", "True Ames Quad", "True Ames Mandala", "Ellis Ericson", "Derrick Disney", "CI Mid 2 + 1", "Channel Islands Tri", "Tyler Warren 5-Fin", "High Pro Twin", "High Speed Quad", "L-Flex", "Power Blade", "Power Glide", "Elmore 10"]
    },
    # --- チャネルアイランズ ---
    {
        "maker": "チャネルアイランズ", "maker_slug": "channel-islands", "shaper": "Al Merrick / Britt Merrick",
        "series": "チャネルアイランズ フィン一覧", "series_slug": "unclassified",
        "model": "CI ログ・ノーズライダー シングルフィン", "slug": "ci-log-noserider-single",
        "product_type": "single-box", "fin_setup": "シングル（1フィン）", "material": "Volan（ボランクロス）", "default_size": "10.0\"",
        "aliases": ["CI Log", "CI Noserider", "Channel Islands Noserider", "Channel Islands TPH", "CI Single Fin", "Channel Islands Dane DD2", "Al Merrick Thruster", "CI TECH 1", "Britt Merrick Twin Surfboard Fins"]
    },
    # --- トーマスサーフボード ---
    {
        "maker": "トーマスサーフボード", "maker_slug": "thomas-surfboards", "shaper": "Thomas Bexon",
        "series": "トーマスサーフボード フィン一覧", "series_slug": "unclassified",
        "model": "トーマス モッドキール・ツインザー", "slug": "thomas-mod-keel",
        "product_type": "futures-plug", "fin_setup": "ツイン・キール（2フィン）", "material": "PG / ファイバーグラス（ソリッド）", "default_size": "L",
        "aliases": ["Thomas Mod Keel", "Thomas Keel", "Thomas Upright Twin", "Thomas Twinzer", "Thomas Quad", "JB Single Fin", "Thomas Bexon", "Thomas Surfboards Volan"]
    },
    # --- エンドルフィン ---
    {
        "maker": "エンドルフィン", "maker_slug": "endorfin", "shaper": "Kelly Slater",
        "series": "ケリースレーター KS1・ツインザー", "series_slug": "endorfin-series",
        "model": "ケリー・スレーター KSR・Tomo カーボン", "slug": "endorfin-ksr",
        "product_type": "futures-plug", "fin_setup": "トライ（3フィン）", "material": "Alpha / カーボンコンポジット", "default_size": "M",
        "aliases": ["Endorfins KSR", "Endorfin KSR", "エンドルフィン KSR", "TOMO MAX KEEL", "ENDORFINS MACHADO", "ENDORFINS X OUTERKNOWN", "ENDORFINS SLATER", "Endorfin Slater", "ファイヤーワイヤー TWIN+2"]
    },
    # --- デフロー ---
    {
        "maker": "デフロー", "maker_slug": "deflow", "shaper": "Deflow Surf",
        "series": "デフロー ツイン・シングル・クアッド", "series_slug": "deflow-series",
        "model": "デフロー シグネチャー フィン", "slug": "deflow-signature",
        "product_type": "futures-plug", "fin_setup": "ツイン・キール（2フィン）", "material": "PG / ファイバーグラス（ソリッド）", "default_size": "L",
        "aliases": ["Finger Fin", "Bowl Cut Fin", "Noserider Fin", "Malibu Fin", "Hus Mix Fin", "Dice Fin"]
    },
]

existing_slugs = {d["slug"] for d in master["devices"]}
for em in EXTRA_FIN_MODELS:
    if em["slug"] not in existing_slugs:
        master["devices"].append(em)
        existing_slugs.add(em["slug"])
        mkr = em["maker"]
        sslug = em["series_slug"]
        if mkr in master["series_groups"] and sslug in master["series_groups"][mkr]:
            master["series_groups"][mkr][sslug]["models"].append(em["slug"])

for p in [
    Path("/var/www/board-search/fin/fin_master.json"),
    Path("/var/www/board-search/fin/scraper/fin_master.json"),
]:
    with open(p, "w", encoding="utf-8") as f:
        json.dump(master, f, ensure_ascii=False, indent=2)

conn = pymysql.connect(host="localhost", user="moto_user", password="moto_pass_2026", database="surfboards_db", charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor)
cur = conn.cursor()

# Purge non-fin items (screws, shims, replacement fin packs for softboards, Catch Surf boards #29, pencils)
cur.execute("""
    UPDATE fins SET is_active = 0
    WHERE shop_id = 29
       OR title REGEXP 'Screw|Shim|Slider|Pencil|Fin Fruit|Replacement Fin Pack|TWIG|Fat Bat|Skipper|Odysea|Demo Surfboard|Single Fin Mid-Length Surfboard|Single Fin Surfboard'
""")
conn.commit()

official_fin_shop_maker = {
    64: "FCS",
    65: "フューチャー",
    66: "トゥルーアムス",
    67: "キャプテンフィン",
    68: "NVS",
    69: "フライングダイアモンド",
    70: "デフロー",
    41: "チャネルアイランズ",
    47: "トーマスサーフボード",
    50: "クリステンソン",
    33: "アルバム",
    48: "デッドクークス",
}

norm = FinNormalizer("/var/www/board-search/fin/fin_master.json")
cur.execute("SELECT * FROM fins WHERE is_active = 1")
rows = cur.fetchall()

for r in rows:
    sid = int(r["shop_id"])
    v_hint = official_fin_shop_maker.get(sid, "")
    res = norm.normalize({
        "title": r["title"],
        "title_en": r["title_en"],
        "description": r["description"],
        "vendor": v_hint,
        "model_code": r["model_code"] or r["source_id"],
        "source_id": r["source_id"],
        "condition_type": r["condition_type"],
    })
    if sid in official_fin_shop_maker and res["maker"] == "その他":
        res["maker"] = official_fin_shop_maker[sid]
        res["maker_sku_key"] = f"{res['maker']}|{res['model_code']}" if res["model_code"] else f"{res['maker']}|{res['model_slug']}|{res['size_code']}"

    cur.execute("""
        UPDATE fins SET
            product_type = %s,
            maker = %s,
            sub_maker = %s,
            shaper = %s,
            series_name = %s,
            series_slug = %s,
            model_name = %s,
            model_slug = %s,
            model_code = %s,
            maker_sku_key = %s,
            display_title = %s,
            fin_system = %s,
            fin_setup = %s,
            size_code = %s,
            size_bucket = %s,
            fin_inch = %s,
            material = %s,
            color = %s,
            raw_color = %s
        WHERE id = %s
    """, (
        res["product_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["display_title"],
        res["fin_system"], res["fin_setup"], res["size_code"], res["size_bucket"], res["fin_inch"],
        res["material"], res["color"], res["raw_color"], r["id"]
    ))
conn.commit()

# Build fin_spec_catalog.json & learned_fin_sku_consensus.json
cur.execute("""
    SELECT model_slug, maker, MAX(model_name) as model_name, MAX(product_type) as pt,
           MAX(fin_system) as fin_sys, MAX(fin_setup) as fin_setup, MAX(material) as mat,
           GROUP_CONCAT(DISTINCT size_code ORDER BY size_code SEPARATOR ',') as sizes,
           COUNT(*) as cnt
    FROM fins
    WHERE is_active = 1 AND model_slug != 'unclassified'
    GROUP BY model_slug, maker
""")
spec_cat = {}
for r in cur.fetchall():
    spec_cat[r["model_slug"]] = {
        "model": r["model_name"],
        "maker": r["maker"],
        "product_type": r["pt"],
        "fin_system": r["fin_sys"],
        "fin_setup": r["fin_setup"],
        "material": r["mat"],
        "sizes": [s for s in (r["sizes"] or "").split(",") if s],
        "active_count": int(r["cnt"]),
    }

for sp in [
    Path("/var/www/board-search/fin/fin_spec_catalog.json"),
    Path("/var/www/board-search/fin/scraper/fin_spec_catalog.json"),
]:
    with open(sp, "w", encoding="utf-8") as f:
        json.dump(spec_cat, 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 maker_sku_key) as skus, MIN(base_price) as min_p, MAX(base_price) as max_p FROM fins WHERE is_active=1")
print("REFINED FIN STATS:", cur.fetchone())
