#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
crawl_wave1_boards.py — BOARD-SEARCH (https://surfboard-search.org)
===================================================================
Comprehensive Wave 1 Direct-Sales Surfboard Crawler covering:
  - Domestic Specialty Used & Vintage Surfboard Shops:
      1. usedsurf (USED SURF × SURF MARKET / STANDARD STORE)
      2. seakong (SEAKONG / シーコング)
      3. bo_doya (ボード屋 / BO-DOYA)
      4. hardoff (ハードオフ・オフハウス サーフボード)
  - Domestic Brand Official & Pro Surf Shops (Shopify UCP API & Direct):
      5. js_jp (JS INDUSTRIES JAPAN 公式)
      6. brine (BRINE 東京世田谷 CHRISTENSON 正規直営)
      7. firewire_jp (FIREWIRE JAPAN 公式)
      8. christenson_jp (CHRISTENSON SURFBOARDS JAPAN 公式)
      9. mar_surf (MAR SURF CREW 東京田端)
  - Overseas Direct-to-Japan Surfboard Megastores (USD / JPY + Intl Shipping + FX Rate):
     10. realwatersports (REAL Watersports USA — www.realwatersports.com)
     11. hawaiiansouthshore (Hawaiian South Shore Honolulu — www.hawaiiansouthshore.com)
     12. cleanlinesurf (Cleanline Surf USA — www.cleanlinesurf.com)
     13. surfstation (The Surf Station Florida — www.surfstationstore.com)
     14. almond_us (Almond Surfboards California — almondsurfboards.com)
"""

import concurrent.futures
import json
import os
import re
import ssl
import sys
import time
import urllib.parse
import urllib.request
from bs4 import BeautifulSoup

SCRAPER_DIR = os.path.dirname(os.path.abspath(__file__))
if SCRAPER_DIR not in sys.path:
    sys.path.insert(0, SCRAPER_DIR)

import db_upsert
import shopify_board_ucp

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Accept-Language": "ja,en-US;q=0.9,en;q=0.8",
}


def fetch_html(url: str, timeout: int = 12) -> str:
    req = urllib.request.Request(url, headers=HEADERS)
    with urllib.request.urlopen(req, context=ctx, timeout=timeout) as r:
        raw = r.read()
        for enc in ("utf-8", "euc_jp", "cp932"):
            try:
                return raw.decode(enc)
            except Exception:
                pass
        return raw.decode("utf-8", "ignore")


# ============================================================================
# 1. USED SURF × SURF MARKET (www.usedsurf.jp)
# ============================================================================
def crawl_usedsurf() -> list:
    items = []
    seen_urls = set()
    cats = [
        "LONG_BOARD",
        "FUN_BOARD",
        "SHORT_BOARD",
        "ALTERNATIVE_BOARD",
        "VINTAGE_BOARD",
        "SURF_MARKET",
    ]
    detail_urls = []
    for cat in cats:
        for page in range(1, 25):
            list_url = f"https://www.usedsurf.jp/product/surfboard/{cat}" if page == 1 else f"https://www.usedsurf.jp/product/surfboard/{cat}?page={page}"
            try:
                html = fetch_html(list_url)
            except Exception:
                break
            found = re.findall(r'href=["\'](https://www\.usedsurf\.jp/product/surfboard/(\d+))["\']', html)
            new_in_pg = 0
            for u, pid in found:
                if u not in seen_urls:
                    seen_urls.add(u)
                    detail_urls.append((u, pid))
                    new_in_pg += 1
            if new_in_pg == 0:
                break

    def parse_detail(u_pid):
        u, pid = u_pid
        try:
            html = fetch_html(u)
            soup = BeautifulSoup(html, "html.parser")
            t_tag = soup.title.text.strip() if soup.title else ""
            title = t_tag.split("|")[0].strip() if "|" in t_tag else t_tag
            if not title or "SOLD" in html.upper() and "カートに入れる" not in html and "お問い合わせ" not in html:
                pass
            spec_map = {}
            for tr in soup.find_all(["tr", "dl"]):
                cells = [c.get_text(" ", strip=True) for c in tr.find_all(["th", "td", "dt", "dd"])]
                if len(cells) >= 2:
                    spec_map[cells[0]] = " ".join(cells[1:])
            full_txt = soup.get_text(" ", strip=True)
            if re.search(r"SOLD\s*OUT|売り切れ|売約済", full_txt, re.I) and "カートに入れる" not in full_txt:
                return None
            pr_str = spec_map.get("Price", "")
            if not pr_str:
                m_p = re.search(r"[￥¥]\s*([\d,]+)\s*(?:（税込）|\(税込\)|円)?", full_txt)
                pr_str = m_p.group(1) if m_p else "0"
            price = int(re.sub(r"[^\d]", "", pr_str) or 0)
            if price < 10000:
                return None

            imgs = []
            for img in soup.find_all("img", src=True):
                src = img["src"]
                if "/upload/save_image/" in src or "/product/" in src or "usedsurf.jp/storage/" in src or "/item/" in src:
                    full_img = src if src.startswith("http") else "https://www.usedsurf.jp" + (src if src.startswith("/") else "/" + src)
                    if full_img not in imgs and not any(x in full_img.lower() for x in ["logo", "banner", "icon", "btn"]):
                        imgs.append(full_img)
            if not imgs:
                for img in soup.find_all("img", src=True):
                    src = img["src"]
                    if any(ext in src.lower() for ext in [".jpg", ".jpeg", ".png", ".webp"]) and not any(x in src.lower() for x in ["logo", "banner", "icon", "common", "header", "footer"]):
                        full_img = src if src.startswith("http") else "https://www.usedsurf.jp" + (src if src.startswith("/") else "/" + src)
                        if full_img not in imgs:
                            imgs.append(full_img)
            if not imgs:
                return None

            cond_str = spec_map.get("Condition", "")
            cond_type = "new" if "NEW" in cond_str.upper() and "USED" not in cond_str.upper() else "used"

            return {
                "source_url": u,
                "source_id": f"us_{pid}",
                "title": spec_map.get("Brand/Model") or title,
                "base_price": price,
                "condition_type": cond_type,
                "length_str": spec_map.get("Size", ""),
                "description": f"Size: {spec_map.get('Size', '')} / Fin: {spec_map.get('Fin', '')} / Weight: {spec_map.get('Weight', '')} / Condition: {cond_str} / Finish: {spec_map.get('Finish', '')} / {full_txt[:1000]}",
                "main_image_url": imgs[0],
                "image_urls": imgs[:8],
            }
        except Exception:
            return None

    with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex:
        for res in ex.map(parse_detail, detail_urls[:450]):
            if res:
                items.append(res)
    return items


# ============================================================================
# 2. シーコング SEAKONG (seakong.shop-pro.jp)
# ============================================================================
def crawl_seakong() -> list:
    items = []
    seen_pids = set()
    # Category cids on seakong.shop-pro.jp (New boards, Used boards, Midlength, Shortboards)
    cat_urls = [
        "https://seakong.shop-pro.jp/?mode=cate&cbid=1322749&csid=0",  # 新品ボード
        "https://seakong.shop-pro.jp/?mode=cate&cbid=1322750&csid=0",  # 中古ボード
        "https://seakong.shop-pro.jp/?mode=srh&keyword=%A5%DC%A1%BC%A5%C9",
        "https://seakong.shop-pro.jp/",
    ]
    for cu in cat_urls:
        for page in range(1, 18):
            u = cu if page == 1 else f"{cu}&page={page}"
            try:
                html = fetch_html(u)
            except Exception:
                break
            pids = re.findall(r"\?pid=(\d+)", html)
            new_cnt = 0
            for pid in pids:
                if pid not in seen_pids:
                    seen_pids.add(pid)
                    new_cnt += 1
            if page == 1 and "?" not in cu:
                break
            if new_cnt == 0:
                break

    def parse_sk(pid):
        u = f"https://seakong.shop-pro.jp/?pid={pid}"
        try:
            html = fetch_html(u)
            if "SOLD OUT" in html.upper() or "売約済" in html or "在庫なし" in html:
                return None
            soup = BeautifulSoup(html, "html.parser")
            title = soup.title.text.split("-")[0].strip() if soup.title else ""
            if not title:
                return None
            spec = {}
            for tr in soup.find_all("tr"):
                cells = [c.get_text(" ", strip=True) for c in tr.find_all(["th", "td"])]
                if len(cells) >= 2:
                    spec[cells[0]] = cells[1]
            full_txt = soup.get_text(" ", strip=True)
            pr_str = spec.get("価格（税込）") or spec.get("販売価格") or ""
            if not pr_str:
                m_p = re.search(r"([\d,]+)\s*円\s*\(税込\)", full_txt)
                pr_str = m_p.group(1) if m_p else "0"
            price = int(re.sub(r"[^\d]", "", pr_str) or 0)
            if price < 15000:
                return None

            imgs = []
            for img in soup.find_all("img", src=True):
                src = img["src"]
                if "img" in src and ("shop-pro.jp" in src or "seakong" in src) and not any(k in src.lower() for k in ["logo", "btn", "icon", "banner", "title"]):
                    full_img = src.split("?")[0] if src.startswith("http") else "https://seakong.shop-pro.jp" + src
                    if full_img not in imgs:
                        imgs.append(full_img)
            if not imgs:
                return None

            brand = spec.get("ブランド", "")
            model = spec.get("モデル", "")
            len_s = spec.get("長さ(ft)", "")
            wid_s = spec.get("幅（inch）", "")
            thk_s = spec.get("厚み（inch）", "")
            wt_s = spec.get("重量(kg)", "")
            fin_s = spec.get("フィン", "")
            mat_s = spec.get("素材", "")
            acc_s = spec.get("付属品", "")

            cond_type = "used" if ("中古" in title or "中古" in full_txt[:400]) else "new"
            wt_val = 0.0
            m_w = re.search(r"(\d+(?:\.\d+)?)", wt_s)
            if m_w:
                wt_val = float(m_w.group(1))

            return {
                "source_url": u,
                "source_id": f"sk_{pid}",
                "vendor": brand,
                "title": f"{brand} {model} {len_s}".strip() if (brand or model) else title,
                "base_price": price,
                "condition_type": cond_type,
                "length_str": len_s,
                "width_str": wid_s,
                "thickness_str": thk_s,
                "weight_kg": wt_val,
                "description": f"ブランド:{brand} モデル:{model} 長さ:{len_s} 幅:{wid_s} 厚み:{thk_s} 重量:{wt_s} フィン:{fin_s} 素材:{mat_s} 付属品:{acc_s} {full_txt[:800]}",
                "main_image_url": imgs[0],
                "image_urls": imgs[:8],
            }
        except Exception:
            return None

    with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex:
        for res in ex.map(parse_sk, list(seen_pids)[:450]):
            if res:
                items.append(res)
    return items


# ============================================================================
# 3. ボード屋 BO-DOYA (bo-doya.com)
# ============================================================================
def crawl_bodoya() -> list:
    items = []
    seen_urls = set()
    genres = [
        ("https://bo-doya.com/item/itemgenre/new-surfboards/", "new"),
        ("https://bo-doya.com/item/itemgenre/used-surfboards-new/", "used"),
        ("https://bo-doya.com/mielengthboards/", "new"),
    ]
    detail_targets = []
    for g_url, c_type in genres:
        for page in range(1, 15):
            u = g_url if page == 1 else f"{g_url}page/{page}/"
            try:
                html = fetch_html(u)
            except Exception:
                break
            links = re.findall(r'href=["\'](https://bo-doya\.com/item/\d+/)["\']', html)
            added = 0
            for lk in links:
                if lk not in seen_urls:
                    seen_urls.add(lk)
                    detail_targets.append((lk, c_type))
                    added += 1
            if added == 0:
                break

    def parse_bd(lk_ct):
        lk, c_type = lk_ct
        try:
            html = fetch_html(lk)
            soup = BeautifulSoup(html, "html.parser")
            brand = ""
            model = ""
            for tr in soup.find_all("tr"):
                cells = [c.get_text(" ", strip=True) for c in tr.find_all(["th", "td"])]
                if len(cells) >= 2:
                    if cells[0] == "ブランド":
                        brand = cells[1]
                    elif cells[0] == "モデル名":
                        model = cells[1]

            imgs = []
            for img in soup.find_all("img", src=True):
                src = img["src"]
                if "/wp-content/uploads/" in src and not any(x in src.lower() for x in ["logo", "banner", "icon", "150x150"]):
                    if src not in imgs:
                        imgs.append(src)
            if not imgs:
                return []

            # ボード屋は1モデルページ内に個別在庫行 (品番 JC-290 | 7'0"／22 1/2"／3 1/8"／51L | ¥122,000) がある
            sub_boards = []
            trs = soup.find_all("tr")
            for idx, tr in enumerate(trs):
                cells = [c.get_text(" ", strip=True) for c in tr.find_all(["th", "td"])]
                if len(cells) == 3 and re.search(r"[¥￥][\d,]+", cells[2]) and re.search(r"[4-9]'|1[01]'", cells[1]):
                    sku = cells[0].strip()
                    dim_txt = cells[1].strip()
                    price = int(re.sub(r"[^\d]", "", cells[2]) or 0)
                    # 次の1〜2行に「売り切れ」やフィンタイプがある
                    next_txt = ""
                    for nxt in trs[idx + 1: idx + 4]:
                        next_txt += " " + nxt.get_text(" ", strip=True)
                    if "売り切れ" in next_txt or "SOLD" in next_txt.upper():
                        continue
                    if price >= 15000:
                        d_parts = [p.strip() for p in re.split(r"[／/]", dim_txt)]
                        l_s = d_parts[0] if len(d_parts) > 0 else ""
                        w_s = d_parts[1] if len(d_parts) > 1 else ""
                        t_s = d_parts[2] if len(d_parts) > 2 else ""
                        v_s = d_parts[3] if len(d_parts) > 3 else ""
                        item_u = f"{lk}?sku={urllib.parse.quote(sku)}"
                        sub_boards.append({
                            "source_url": item_u,
                            "source_id": f"bd_{sku}",
                            "vendor": brand,
                            "model_code": sku,
                            "title": f"{brand} {model} {l_s} {v_s} [{sku}]".strip(),
                            "base_price": price,
                            "condition_type": "used" if ("中古" in next_txt or c_type == "used") else "new",
                            "length_str": l_s,
                            "width_str": w_s,
                            "thickness_str": t_s,
                            "volume_str": v_s,
                            "description": f"{brand} {model} サイズ:{dim_txt} {next_txt}",
                            "main_image_url": imgs[0],
                            "image_urls": imgs[:8],
                        })
            return sub_boards
        except Exception:
            return []

    with concurrent.futures.ThreadPoolExecutor(max_workers=6) as ex:
        for res_list in ex.map(parse_bd, detail_targets[:180]):
            if res_list:
                items.extend(res_list)
    return items


# ============================================================================
# 4. ハードオフ・オフハウス オフモール (netmall.hardoff.co.jp)
# ============================================================================
def crawl_hardoff_surf() -> list:
    items = []
    seen_pids = set()
    for page in range(1, 15):
        u = f"https://netmall.hardoff.co.jp/search/?q=%E3%82%B5%E3%83%BC%E3%83%95%E3%83%9C%E3%83%BC%E3%83%89&exso=1&s=2&p={page}"
        try:
            html = fetch_html(u)
        except Exception:
            break
        pids = re.findall(r"https://netmall\.hardoff\.co\.jp/product/(\d+)/", html)
        new_cnt = 0
        for pid in pids:
            if pid not in seen_pids:
                seen_pids.add(pid)
                new_cnt += 1
        if new_cnt == 0:
            break

    def parse_ho(pid):
        u = f"https://netmall.hardoff.co.jp/product/{pid}/"
        try:
            html = fetch_html(u)
            if "カートに入れる" not in html:
                return None
            soup = BeautifulSoup(html, "html.parser")
            h1 = soup.find("h1")
            title = h1.get_text(" ", strip=True) if h1 else (soup.title.text.split("|")[0].strip() if soup.title else "")
            spec = {}
            for tr in soup.find_all("tr"):
                cells = [c.get_text(" ", strip=True) for c in tr.find_all(["th", "td"])]
                if len(cells) >= 2:
                    spec[cells[0]] = cells[1]
            full_txt = soup.get_text(" ", strip=True)
            m_p = re.search(r"([\d,]+)\s*円\s*(?:\(税込\)|（税込）)?", full_txt)
            price = int(re.sub(r"[^\d]", "", m_p.group(1)) if m_p else 0)
            if price < 10000:
                return None

            brand = spec.get("ブランド", "") or spec.get("メーカー", "")
            model = spec.get("型番", "") or spec.get("モデル名", "")
            feat = spec.get("特徴・備考", "")

            imgs = []
            for img in soup.find_all("img", src=True):
                src = img["src"]
                if "imageflux.jp" in src or "/product/" in src:
                    hi = re.sub(r"w=\d+,h=\d+", "w=800,h=800", src)
                    if hi not in imgs:
                        imgs.append(hi)
            if not imgs:
                return None

            return {
                "source_url": u,
                "source_id": f"ho_{pid}",
                "vendor": brand,
                "title": f"{brand} {title} {model}".strip(),
                "base_price": price,
                "condition_type": "used",
                "description": f"{brand} {title} {model} {feat}",
                "main_image_url": imgs[0],
                "image_urls": imgs[:8],
            }
        except Exception:
            return None

    with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex:
        for res in ex.map(parse_ho, list(seen_pids)[:300]):
            if res:
                items.append(res)
    return items


# ============================================================================
# 5. MAR SURF CREW (www.mar-surf.com)
# ============================================================================
def crawl_marsurf() -> list:
    items = []
    seen_urls = set()
    cat_urls = [
        "https://www.mar-surf.com/categories/3591866",  # サーフボード全体
        "https://www.mar-surf.com/categories/3601821",  # Christenson
        "https://www.mar-surf.com/categories/3601827",  # Lost
        "https://www.mar-surf.com/categories/3601831",  # Channel Islands
        "https://www.mar-surf.com/categories/3601833",  # Firewire
        "https://www.mar-surf.com/categories/3601840",  # Libtech
        "https://www.mar-surf.com/categories/3959478",  # DHD
    ]
    item_urls = []
    for cu in cat_urls:
        try:
            html = fetch_html(cu)
            found = re.findall(r'href=["\'](https://www\.mar-surf\.com/items/(\d+))["\']', html)
            for u, iid in found:
                if u not in seen_urls:
                    seen_urls.add(u)
                    item_urls.append((u, iid))
        except Exception:
            pass

    def parse_ms(u_id):
        u, iid = u_id
        try:
            html = fetch_html(u)
            if "SOLD OUT" in html.upper():
                return None
            soup = BeautifulSoup(html, "html.parser")
            title = soup.title.text.split("|")[0].strip() if soup.title else ""
            full_txt = soup.get_text(" ", strip=True)
            m_p = re.search(r"[¥￥]\s*([\d,]+)", full_txt)
            price = int(re.sub(r"[^\d]", "", m_p.group(1)) if m_p else 0)
            if price < 30000:
                return None
            imgs = []
            for img in soup.find_all("img", src=True):
                src = img["src"]
                if "base-ec2if.akamaized.net/images/item/" in src or "base.shop" in src or "thebase.in/img/" in src:
                    if src not in imgs:
                        imgs.append(src)
            if not imgs:
                return None
            return {
                "source_url": u,
                "source_id": f"ms_{iid}",
                "title": title,
                "base_price": price,
                "condition_type": "used" if "中古" in title else "new",
                "description": full_txt[:1500],
                "main_image_url": imgs[0],
                "image_urls": imgs[:8],
            }
        except Exception:
            return None

    with concurrent.futures.ThreadPoolExecutor(max_workers=6) as ex:
        for res in ex.map(parse_ms, item_urls[:250]):
            if res:
                items.append(res)
    return items


# ============================================================================
# 6. Shopify UCP API 国内外ショップ一括取得
# ============================================================================
UCP_SHOPS = [
    # 国内公式
    ("js_jp",              "www.jsindustries.jp",        ["Surfboard", "Xero", "Monsta", "Baron"], 3, "JPY", "JP"),
    ("brine",              "brine.jp",                   ["サーフボード", "CHRISTENSON"], 2, "JPY", "JP"),
    ("firewire_jp",        "firewirejapan.com",          ["", "Surfboard"], 2, "JPY", "JP"),
    ("christenson_jp",     "christensonsurfboards.jp",   ["", "Surfboard"], 2, "JPY", "JP"),
    # 海外直販 (日本発送対応: USD / JPY + 日本向け国際送料 + 日次為替レート換算)
    ("realwatersports",    "www.realwatersports.com",    ["surfboard", "Firewire", "Channel Islands", "Lost"], 3, "USD", "US"),
    ("hawaiiansouthshore", "www.hawaiiansouthshore.com", ["surfboard", "Lost", "Channel Islands", "Firewire"], 3, "JPY", "JP"),
    ("cleanlinesurf",      "www.cleanlinesurf.com",      ["surfboard", "Firewire", "Channel Islands", "Lost"], 3, "USD", "US"),
    ("surfstation",        "www.surfstationstore.com",   ["surfboard", "Channel Islands", "Lost", "Used Surfboard"], 3, "USD", "US"),
    ("almond_us",          "almondsurfboards.com",       ["surfboard", "Walks on Water", "Joy"], 2, "JPY", "JP"),
]


def run_all():
    conn = db_upsert.get_connection()
    fx_map = db_upsert.sync_daily_fx_rates(conn)
    print(f"Synced FX rates: {fx_map}")

    # 1. Shopify UCP Shops
    for shop_key, dom, queries, max_pg, curr, country in UCP_SHOPS:
        t0 = time.time()
        try:
            existing = db_upsert.get_existing_shop_urls(conn, db_upsert.SHOP_INFO_MAP[shop_key]["id"])
            raw_list = shopify_board_ucp.fetch_ucp_catalog(dom, queries=queries, max_pages_per_query=max_pg, currency=curr, country=country)
            seen = set()
            upserted = 0
            for it in raw_list:
                res = db_upsert.upsert_board_item(conn, shop_key, it, fx_map=fx_map)
                if res == "upserted":
                    seen.add(it["source_url"])
                    upserted += 1
            conn.commit()
            rep = db_upsert.finalize_shop_scrape(conn, shop_key, seen, existing, new_count=upserted)
            print(f"[UCP {shop_key:18s}] raw={len(raw_list):4d} -> active={rep['live_count']:4d} ({time.time()-t0:.1f}s)")
        except Exception as e:
            print(f"[UCP ERR {shop_key}] {e}")

    # 2. Custom HTML Domestic Shops
    html_crawlers = [
        ("usedsurf", crawl_usedsurf),
        ("seakong", crawl_seakong),
        ("bo_doya", crawl_bodoya),
        ("hardoff", crawl_hardoff_surf),
        ("mar_surf", crawl_marsurf),
    ]
    for shop_key, fn in html_crawlers:
        t0 = time.time()
        try:
            existing = db_upsert.get_existing_shop_urls(conn, db_upsert.SHOP_INFO_MAP[shop_key]["id"])
            raw_list = fn()
            seen = set()
            upserted = 0
            for it in raw_list:
                res = db_upsert.upsert_board_item(conn, shop_key, it, fx_map=fx_map)
                if res == "upserted":
                    seen.add(it["source_url"])
                    upserted += 1
            conn.commit()
            rep = db_upsert.finalize_shop_scrape(conn, shop_key, seen, existing, new_count=upserted)
            print(f"[HTML {shop_key:17s}] raw={len(raw_list):4d} -> active={rep['live_count']:4d} ({time.time()-t0:.1f}s)")
        except Exception as e:
            print(f"[HTML ERR {shop_key}] {e}")

    with conn.cursor() as cur:
        cur.execute("SELECT COUNT(*) AS total, SUM(CASE WHEN condition_type='new' THEN 1 ELSE 0 END) AS new_c, SUM(CASE WHEN condition_type='used' THEN 1 ELSE 0 END) AS used_c FROM boards WHERE is_active = 1")
        tot = cur.fetchone()
        print(f"=== WAVE 1 TOTAL ACTIVE BOARDS: {tot['total']} (New: {tot['new_c']}, Used: {tot['used_c']}) ===")
    conn.close()


if __name__ == "__main__":
    run_all()
