#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Shared DB Upsert, Daily FX Rate Sync & 4-Layer Safety Guard Module for BOARD-SEARCH (surfboards_db)
"""

import datetime
import json
import os
import pymysql
from board_normalizer import BoardNormalizer

DB_CONFIG = {
    "host": "localhost",
    "user": "moto_user",
    "password": "moto_pass_2026",
    "database": "surfboards_db",
    "charset": "utf8mb4",
    "cursorclass": pymysql.cursors.DictCursor,
}

SHOP_INFO_MAP = {
    "usedsurf":          {"id": 1,  "name": "USED SURF × SURF MARKET（STANDARD STORE）", "url": "https://www.usedsurf.jp/",            "min_expected": 30, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "神奈川県"},
    "seakong":           {"id": 2,  "name": "シーコング（SEAKONG）",                     "url": "https://seakong.shop-pro.jp/",        "min_expected": 30, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 0,     "prefecture": "神奈川県"},
    "bo_doya":           {"id": 3,  "name": "ボード屋（BO-DOYA）",                       "url": "https://bo-doya.com/",                "min_expected": 15, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 0,     "prefecture": "東京都"},
    "js_jp":             {"id": 4,  "name": "JS INDUSTRIES JAPAN 公式",                  "url": "https://www.jsindustries.jp/",        "min_expected": 20, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "千葉県"},
    "luvsurf":           {"id": 5,  "name": "Luvsurf（LOST & PLACEBO 総代理店）",        "url": "https://www.luvsurf.co.jp/",          "min_expected": 15, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "東京都"},
    "brine":             {"id": 6,  "name": "BRINE（ブライン / CHRISTENSON 正規直営）",  "url": "https://brine.jp/",                   "min_expected": 10, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "東京都"},
    "firewire_jp":       {"id": 7,  "name": "FIREWIRE JAPAN 公式",                       "url": "https://firewirejapan.com/",          "min_expected": 5,  "is_overseas": 0, "currency": "JPY", "shipping_jpy": 0,     "prefecture": "神奈川県"},
    "christenson_jp":    {"id": 8,  "name": "CHRISTENSON SURFBOARDS JAPAN 公式",         "url": "https://christensonsurfboards.jp/",   "min_expected": 5,  "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "愛知県"},
    "ci_jp":             {"id": 9,  "name": "CHANNEL ISLANDS SURFBOARDS JAPAN 公式",     "url": "https://cisurfboards.jp/",            "min_expected": 5,  "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "東京都"},
    "boardriders_jp":    {"id": 10, "name": "BOARDRIDERS JAPAN 公式",                    "url": "https://boardriders.co.jp/",          "min_expected": 5,  "is_overseas": 0, "currency": "JPY", "shipping_jpy": 5500,  "prefecture": "東京都"},
    "mar_surf":          {"id": 11, "name": "MAR SURF CREW（マールサーフクルー）",       "url": "https://www.mar-surf.com/",           "min_expected": 10, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "東京都"},
    "jack_surf":         {"id": 12, "name": "ジャックオーシャンスポーツ",                "url": "https://www.jack-surf.com/",          "min_expected": 20, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "静岡県"},
    "breakout":          {"id": 13, "name": "BREAKOUT（ブレイクアウト福岡）",            "url": "https://www.breakout-jp.com/",        "min_expected": 10, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "福岡県"},
    "follows":           {"id": 14, "name": "FOLLOWS（フォローズ）",                     "url": "https://www.follows.co.jp/",          "min_expected": 10, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "岐阜県"},
    "nakisurf":          {"id": 15, "name": "NAKISURF（ナキサーフ千葉一宮）",            "url": "https://www.nakisurf.com/",           "min_expected": 10, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "千葉県"},
    "deadkooks_shonan":  {"id": 16, "name": "DEAD KOOKS SHONAN（湘南旗艦店）",           "url": "https://www.deadkooks-shonan.com/",   "min_expected": 5,  "is_overseas": 0, "currency": "JPY", "shipping_jpy": 6600,  "prefecture": "神奈川県"},
    "oshmans":           {"id": 17, "name": "OSHMAN'S（オッシュマンズ公式）",            "url": "https://www.oshmans.co.jp/",          "min_expected": 5,  "is_overseas": 0, "currency": "JPY", "shipping_jpy": 5500,  "prefecture": "東京都"},
    "murasaki":          {"id": 18, "name": "ムラサキスポーツ公式",                      "url": "https://www.murasaki.jp/",            "min_expected": 20, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 0,     "prefecture": "東京都"},
    "hardoff":           {"id": 19, "name": "ハードオフ・オフハウス（オフモール）",      "url": "https://netmall.hardoff.co.jp/",      "min_expected": 10, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 5500,  "prefecture": "全国"},
    "trefac_sports":     {"id": 20, "name": "トレファクスポーツアウトドア",              "url": "https://www.treasure-f.com/",         "min_expected": 10, "is_overseas": 0, "currency": "JPY", "shipping_jpy": 5500,  "prefecture": "全国"},
    "realwatersports":   {"id": 21, "name": "REAL Watersports (USA)",                    "url": "https://www.realwatersports.com/",    "min_expected": 50, "is_overseas": 1, "currency": "USD", "shipping_jpy": 28000, "prefecture": "海外（USA）"},
    "hawaiiansouthshore":{"id": 22, "name": "Hawaiian South Shore (Hawaii / USA)",       "url": "https://www.hawaiiansouthshore.com/", "min_expected": 50, "is_overseas": 1, "currency": "JPY", "shipping_jpy": 24000, "prefecture": "海外（Hawaii）"},
    "cleanlinesurf":     {"id": 23, "name": "Cleanline Surf (USA)",                      "url": "https://www.cleanlinesurf.com/",      "min_expected": 30, "is_overseas": 1, "currency": "USD", "shipping_jpy": 28000, "prefecture": "海外（USA）"},
    "surfstation":       {"id": 24, "name": "The Surf Station (USA)",                    "url": "https://www.surfstationstore.com/",   "min_expected": 50, "is_overseas": 1, "currency": "USD", "shipping_jpy": 28000, "prefecture": "海外（USA）"},
    "almond_us":         {"id": 25, "name": "Almond Surfboards (California Official)",   "url": "https://almondsurfboards.com/",       "min_expected": 10, "is_overseas": 1, "currency": "JPY", "shipping_jpy": 29000, "prefecture": "海外（California）"},
    "pukas_es":          {"id": 26, "name": "Pukas Surf Shop (Europe / Spain)",          "url": "https://pukassurfshop.com/",          "min_expected": 10, "is_overseas": 1, "currency": "EUR", "shipping_jpy": 32000, "prefecture": "海外（Europe）"},
}

_NORMALIZER = None


def get_normalizer() -> BoardNormalizer:
    global _NORMALIZER
    if _NORMALIZER is None:
        _NORMALIZER = BoardNormalizer()
    return _NORMALIZER


def get_connection():
    return pymysql.connect(**DB_CONFIG)


def sync_daily_fx_rates(conn) -> dict:
    """
    Reads /var/www/html/cache/fx_rates.json (shared across MotoSearch / CarSearch / WatchSearch)
    and updates fx_rates table, returning {currency: (rate_to_jpy, rate_date_str)}.
    """
    today_str = datetime.date.today().isoformat()
    rates = {
        "JPY": (1.0, today_str),
        "USD": (154.80, today_str),
        "EUR": (163.50, today_str),
        "AUD": (101.20, today_str),
        "GBP": (196.40, today_str),
    }
    fx_cache_path = "/var/www/html/cache/fx_rates.json"
    if os.path.exists(fx_cache_path):
        try:
            with open(fx_cache_path, "r", encoding="utf-8") as f:
                data = json.load(f)
            r_dict = data.get("rates") or data
            r_date = str(data.get("date") or today_str)[:10]
            for c in ("USD", "EUR", "AUD", "GBP"):
                v = float(r_dict.get(c) or 0)
                if v > 10.0:
                    rates[c] = (round(v, 4), r_date)
                elif 0.001 < v < 0.1:
                    # 1 JPY -> X USD の逆数の場合
                    rates[c] = (round(1.0 / v, 4), r_date)
        except Exception:
            pass

    with conn.cursor() as cur:
        for curr, (rt, dt) in rates.items():
            cur.execute(
                """
                INSERT INTO fx_rates (currency, rate_to_jpy, rate_date)
                VALUES (%s, %s, %s)
                ON DUPLICATE KEY UPDATE rate_to_jpy = VALUES(rate_to_jpy), rate_date = VALUES(rate_date)
                """,
                (curr, rt, dt),
            )
    conn.commit()
    return rates


def compute_board_shipping_jpy(shop_key: str, length_total_in: float, is_free_flag: bool = False) -> tuple:
    sinfo = SHOP_INFO_MAP.get(shop_key, {})
    if is_free_flag or sinfo.get("shipping_jpy") == 0:
        return 0, 1, "送料無料（または店頭受取無料）"
    base_ship = int(sinfo.get("shipping_jpy") or 6600)
    if sinfo.get("is_overseas"):
        # 海外ボード長に応じた段階国際エアカーゴ送料 (ショート: ¥24,000〜¥28,000 / ミッド: ¥31,000 / ロング: ¥36,000)
        if length_total_in >= 106.0:
            ship = max(base_ship, 36000)
        elif length_total_in >= 80.0:
            ship = max(base_ship, 31000)
        else:
            ship = base_ship
        return ship, 0, f"＋ 日本向け推定国際送料 ¥{ship:,}"
    else:
        if length_total_in >= 106.0:
            ship = max(base_ship, 9900)
        elif length_total_in >= 80.0:
            ship = max(base_ship, 7700)
        else:
            ship = base_ship
        return ship, 0, f"＋ 送料 ¥{ship:,}（西濃運輸 営業所留め）"


def get_existing_shop_urls(conn, shop_id: int) -> dict:
    with conn.cursor() as cur:
        cur.execute(
            "SELECT id, source_url, is_active, base_price, image_urls FROM boards WHERE shop_id = %s AND (is_c2c = 0 OR is_c2c IS NULL)",
            (shop_id,),
        )
        rows = cur.fetchall()
    return {r["source_url"]: r for r in rows}


def upsert_board_item(conn, shop_key: str, raw_item: dict, fx_map: dict = None) -> str:
    sinfo = SHOP_INFO_MAP.get(shop_key)
    if not sinfo:
        return "skipped"
    shop_id = sinfo["id"]
    source_url = str(raw_item.get("source_url") or "").strip()
    if not source_url:
        return "skipped"

    norm = get_normalizer()
    orig_curr = str(raw_item.get("original_currency") or sinfo.get("currency") or "JPY").upper()
    orig_price = float(raw_item.get("original_price") or raw_item.get("base_price") or 0.0)
    if fx_map is None:
        fx_map = {"JPY": (1.0, datetime.date.today().isoformat()), "USD": (154.80, datetime.date.today().isoformat()), "EUR": (163.50, datetime.date.today().isoformat())}
    fx_rate, fx_date = fx_map.get(orig_curr, (1.0, datetime.date.today().isoformat()))

    if orig_curr != "JPY" and orig_price > 0:
        base_price = int(round(orig_price * fx_rate))
    else:
        base_price = int(round(float(raw_item.get("base_price") or orig_price or -1)))
        orig_price = float(base_price) if base_price > 0 else 0.0

    if base_price >= 20000000 or str(base_price).endswith("999998") or str(base_price).endswith("999999"):
        return "skipped"
    if base_price <= 0 and base_price != -1:
        return "skipped"

    if norm.is_accessory(raw_item.get("title", ""), raw_item.get("category_hint", ""), base_price):
        return "skipped"

    raw_item["shop_id"] = shop_id
    raw_item["base_price"] = base_price
    ndata = norm.normalize(raw_item)

    ship_jpy, is_free, ship_label = compute_board_shipping_jpy(
        shop_key, ndata["length_total_in"], is_free_flag=bool(raw_item.get("is_free_shipping"))
    )
    total_price = (base_price + (ship_jpy or 0)) if base_price > 0 else -1

    image_urls = raw_item.get("image_urls") or []
    main_img = str(raw_item.get("main_image_url") or (image_urls[0] if image_urls else "")).strip()
    if not main_img or "no-img" in main_img or "no_image" in main_img:
        return "skipped"
    if not image_urls:
        image_urls = [main_img]
    image_urls_json = json.dumps(image_urls[:12], ensure_ascii=False)

    sql = """
        INSERT INTO boards (
            shop_id, source_url, source_id, is_c2c,
            product_type, origin_type, maker, sub_maker, shaper,
            series_name, series_slug, model_name, model_slug, model_code,
            title, title_en, display_title,
            base_price, total_price, original_currency, original_price,
            shipping_jpy, is_free_shipping, shipping_method, shipping_label,
            fx_rate, fx_date,
            condition_type, condition_rank, repair_status, footmark_rank,
            length_ft, length_in, length_total_in, length_cm, length_display, length_bucket,
            width_in, width_display, thickness_in, thickness_display, dimension_display,
            volume_cl, is_volume_estimated, volume_bucket, weight_kg,
            fin_system, fin_setup, material, tail_shape,
            has_fins, has_case, accessories,
            color, raw_color, warranty,
            prefecture, city_address, store_name,
            description, main_image_url, image_urls, dedup_hash,
            is_active, scraped_at
        ) VALUES (
            %(shop_id)s, %(source_url)s, %(source_id)s, 0,
            %(product_type)s, %(origin_type)s, %(maker)s, %(sub_maker)s, %(shaper)s,
            %(series_name)s, %(series_slug)s, %(model_name)s, %(model_slug)s, %(model_code)s,
            %(title)s, %(title_en)s, %(display_title)s,
            %(base_price)s, %(total_price)s, %(original_currency)s, %(original_price)s,
            %(shipping_jpy)s, %(is_free_shipping)s, %(shipping_method)s, %(shipping_label)s,
            %(fx_rate)s, %(fx_date)s,
            %(condition_type)s, %(condition_rank)s, %(repair_status)s, %(footmark_rank)s,
            %(length_ft)s, %(length_in)s, %(length_total_in)s, %(length_cm)s, %(length_display)s, %(length_bucket)s,
            %(width_in)s, %(width_display)s, %(thickness_in)s, %(thickness_display)s, %(dimension_display)s,
            %(volume_cl)s, %(is_volume_estimated)s, %(volume_bucket)s, %(weight_kg)s,
            %(fin_system)s, %(fin_setup)s, %(material)s, %(tail_shape)s,
            %(has_fins)s, %(has_case)s, %(accessories)s,
            %(color)s, %(raw_color)s, %(warranty)s,
            %(prefecture)s, %(city_address)s, %(store_name)s,
            %(description)s, %(main_image_url)s, %(image_urls_json)s, %(dedup_hash)s,
            1, NOW()
        )
        ON DUPLICATE KEY UPDATE
            shop_id = VALUES(shop_id),
            source_id = VALUES(source_id),
            product_type = VALUES(product_type),
            origin_type = VALUES(origin_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),
            title = VALUES(title),
            title_en = VALUES(title_en),
            display_title = VALUES(display_title),
            base_price = VALUES(base_price),
            total_price = VALUES(total_price),
            original_currency = VALUES(original_currency),
            original_price = VALUES(original_price),
            shipping_jpy = VALUES(shipping_jpy),
            is_free_shipping = VALUES(is_free_shipping),
            shipping_method = VALUES(shipping_method),
            shipping_label = VALUES(shipping_label),
            fx_rate = VALUES(fx_rate),
            fx_date = VALUES(fx_date),
            condition_type = VALUES(condition_type),
            condition_rank = VALUES(condition_rank),
            repair_status = VALUES(repair_status),
            footmark_rank = VALUES(footmark_rank),
            length_ft = VALUES(length_ft),
            length_in = VALUES(length_in),
            length_total_in = VALUES(length_total_in),
            length_cm = VALUES(length_cm),
            length_display = VALUES(length_display),
            length_bucket = VALUES(length_bucket),
            width_in = VALUES(width_in),
            width_display = VALUES(width_display),
            thickness_in = VALUES(thickness_in),
            thickness_display = VALUES(thickness_display),
            dimension_display = VALUES(dimension_display),
            volume_cl = VALUES(volume_cl),
            is_volume_estimated = VALUES(is_volume_estimated),
            volume_bucket = VALUES(volume_bucket),
            weight_kg = VALUES(weight_kg),
            fin_system = VALUES(fin_system),
            fin_setup = VALUES(fin_setup),
            material = VALUES(material),
            tail_shape = VALUES(tail_shape),
            has_fins = VALUES(has_fins),
            has_case = VALUES(has_case),
            accessories = VALUES(accessories),
            color = VALUES(color),
            raw_color = VALUES(raw_color),
            warranty = VALUES(warranty),
            prefecture = VALUES(prefecture),
            city_address = VALUES(city_address),
            store_name = VALUES(store_name),
            description = VALUES(description),
            main_image_url = VALUES(main_image_url),
            image_urls = IF(JSON_LENGTH(VALUES(image_urls)) >= JSON_LENGTH(COALESCE(image_urls, '[]')), VALUES(image_urls), image_urls),
            dedup_hash = VALUES(dedup_hash),
            is_active = 1,
            scraped_at = NOW()
    """
    params = {
        **ndata,
        "shop_id": shop_id,
        "source_url": source_url[:512],
        "source_id": str(raw_item.get("source_id") or "")[:128],
        "base_price": base_price,
        "total_price": total_price,
        "original_currency": orig_curr,
        "original_price": orig_price,
        "shipping_jpy": ship_jpy,
        "is_free_shipping": is_free,
        "shipping_method": "国際エアカーゴ配送" if sinfo.get("is_overseas") else "西濃運輸 営業所留め",
        "shipping_label": ship_label[:128],
        "fx_rate": fx_rate,
        "fx_date": fx_date,
        "warranty": "保証付" if ndata["condition_type"] == "new" else "無し",
        "prefecture": str(raw_item.get("prefecture") or sinfo.get("prefecture") or "東京都")[:50],
        "city_address": str(raw_item.get("city_address") or "")[:128],
        "store_name": str(raw_item.get("store_name") or sinfo["name"])[:128],
        "description": str(raw_item.get("description") or "")[:4000],
        "main_image_url": main_img[:512],
        "image_urls_json": image_urls_json,
    }
    with conn.cursor() as cur:
        cur.execute(sql, params)
    return "upserted"


def finalize_shop_scrape(
    conn,
    shop_key: str,
    seen_urls: set,
    existing_map: dict,
    new_count: int = 0,
    had_error: bool = False,
    error_msg: str = "",
) -> dict:
    s_info = SHOP_INFO_MAP.get(shop_key, {"id": 0, "name": shop_key, "url": "", "min_expected": 5})
    shop_id = s_info["id"]
    shop_name = s_info["name"]
    shop_url = s_info["url"]
    min_expected = s_info["min_expected"]

    prev_active = sum(1 for r in existing_map.values() if int(r.get("is_active") or 0) == 1)
    live_count = len(seen_urls)

    if live_count == 0:
        return {
            "ok": False, "shop_id": shop_id, "shop_key": shop_key, "shop_name": shop_name, "url": shop_url,
            "prev_active": prev_active, "live_count": 0, "new_count": new_count, "sold_count": 0,
            "reason": error_msg or f"取得件数0件 (前回稼働: {prev_active}本) - Guard 2発動により売約除外をスキップ",
        }

    if had_error:
        return {
            "ok": False, "shop_id": shop_id, "shop_key": shop_key, "shop_name": shop_name, "url": shop_url,
            "prev_active": prev_active, "live_count": live_count, "new_count": new_count, "sold_count": 0,
            "reason": f"{error_msg} - 巡回途中エラーのため売約除外をスキップ",
        }

    if prev_active >= 10 and (live_count < prev_active * 0.5 or live_count < min(min_expected, prev_active * 0.5)):
        return {
            "ok": False, "shop_id": shop_id, "shop_key": shop_key, "shop_name": shop_name, "url": shop_url,
            "prev_active": prev_active, "live_count": live_count, "new_count": new_count, "sold_count": 0,
            "reason": f"一覧取得数が50%未満に激減 ({live_count}本 / 前回稼働 {prev_active}本) - Guard 1発動により売約除外を停止",
        }

    sold_urls = [u for u, r in existing_map.items() if int(r.get("is_active") or 0) == 1 and u not in seen_urls]
    sold_deactivated = 0
    if sold_urls and shop_id and shop_id != 999:
        with conn.cursor() as cur:
            for i in range(0, len(sold_urls), 500):
                chunk = sold_urls[i:i + 500]
                ph = ",".join(["%s"] * len(chunk))
                cur.execute(
                    f"UPDATE boards SET is_active = 0 WHERE shop_id = %s AND (is_c2c = 0 OR is_c2c IS NULL) AND shop_id != 999 AND source_url IN ({ph})",
                    [shop_id] + chunk,
                )
                sold_deactivated += cur.rowcount
        conn.commit()

    with conn.cursor() as cur:
        cur.execute(
            "SELECT COUNT(*) AS cnt FROM boards WHERE shop_id = %s AND is_active = 1 AND (is_c2c = 0 OR is_c2c IS NULL)",
            (shop_id,),
        )
        post_active = int(cur.fetchone()["cnt"])

    return {
        "ok": True, "shop_id": shop_id, "shop_key": shop_key, "shop_name": shop_name, "url": shop_url,
        "prev_active": prev_active, "live_count": post_active, "new_count": new_count, "sold_count": sold_deactivated,
        "reason": "",
    }
