"""
GH ログインフォーム構造調査スクリプト

headless=True で GH 管理画面のログインページを開き、
フォーム要素の実際の構造（input/button/form）を
login_form_dump.txt と login_form.png に保存する。

Usage:
    python debug_login_form.py

出力:
    python/tools/login_form_dump.txt  -- フォーム要素一覧
    python/tools/login_form.png       -- ページスクリーンショット
"""

import sys
from datetime import datetime
from pathlib import Path

from playwright.sync_api import sync_playwright

GH_LOGIN_URL = "https://manager.girlsheaven-job.net/"
PAGE_TIMEOUT = 30_000

OUT_DIR = Path(__file__).parent
TXT_OUT = OUT_DIR / "login_form_dump.txt"
PNG_OUT = OUT_DIR / "login_form.png"


def collect_form_info(page) -> list[str]:
    lines = [
        "=== GH ログインフォーム構造調査 ===",
        f"生成日時: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
        f"URL: {page.url}",
        f"タイトル: {page.title()}",
        "",
    ]

    # ── <form> 要素 ──────────────────────────────────────────────────────────
    lines.append("【form 要素】")
    forms = page.query_selector_all("form")
    if forms:
        for i, form in enumerate(forms):
            action = form.get_attribute("action") or "(なし)"
            method = form.get_attribute("method") or "(なし)"
            id_    = form.get_attribute("id")    or "(なし)"
            cls    = form.get_attribute("class") or "(なし)"
            lines.append(f"  form[{i}] id={id_!r} class={cls!r} action={action!r} method={method!r}")
    else:
        lines.append("  (form 要素が見つかりません)")
    lines.append("")

    # ── <input> 要素 ─────────────────────────────────────────────────────────
    lines.append("【input 要素（全件）】")
    inputs = page.query_selector_all("input")
    if inputs:
        for inp in inputs:
            id_    = inp.get_attribute("id")          or ""
            name   = inp.get_attribute("name")        or ""
            type_  = inp.get_attribute("type")        or ""
            ph     = inp.get_attribute("placeholder") or ""
            value  = inp.get_attribute("value")       or ""
            cls    = inp.get_attribute("class")       or ""
            lines.append(
                f"  <input> id={id_!r} name={name!r} type={type_!r} "
                f"placeholder={ph!r} value={value!r} class={cls!r}"
            )
    else:
        lines.append("  (input 要素が見つかりません)")
    lines.append("")

    # ── <button> 要素 ────────────────────────────────────────────────────────
    lines.append("【button 要素（全件）】")
    buttons = page.query_selector_all("button")
    if buttons:
        for btn in buttons:
            id_   = btn.get_attribute("id")    or ""
            name  = btn.get_attribute("name")  or ""
            type_ = btn.get_attribute("type")  or ""
            cls   = btn.get_attribute("class") or ""
            try:
                text = btn.inner_text().strip()[:80]
            except Exception:
                text = ""
            lines.append(
                f"  <button> id={id_!r} name={name!r} type={type_!r} "
                f"class={cls!r} text={text!r}"
            )
    else:
        lines.append("  (button 要素が見つかりません)")
    lines.append("")

    # ── type=submit の input ─────────────────────────────────────────────────
    lines.append("【type=submit の input】")
    submits = page.query_selector_all("input[type='submit']")
    if submits:
        for s in submits:
            id_   = s.get_attribute("id")    or ""
            name  = s.get_attribute("name")  or ""
            value = s.get_attribute("value") or ""
            cls   = s.get_attribute("class") or ""
            lines.append(f"  <input type=submit> id={id_!r} name={name!r} value={value!r} class={cls!r}")
    else:
        lines.append("  (なし)")
    lines.append("")

    # ── 「ログイン」を含む要素 ───────────────────────────────────────────────
    lines.append("【「ログイン」を含む要素（button / input[submit] / a）】")
    found_login = []
    for sel in ["button", "input[type='submit']", "a"]:
        els = page.query_selector_all(sel)
        for el in els:
            try:
                text = el.inner_text().strip()
            except Exception:
                text = ""
            value = el.get_attribute("value") or ""
            if "ログイン" in text or "ログイン" in value:
                id_  = el.get_attribute("id")    or ""
                name = el.get_attribute("name")  or ""
                cls  = el.get_attribute("class") or ""
                found_login.append(
                    f"  {sel} id={id_!r} name={name!r} class={cls!r} "
                    f"text={text[:60]!r} value={value!r}"
                )
    if found_login:
        lines.extend(found_login)
    else:
        lines.append("  (「ログイン」を含む要素が見つかりません)")
    lines.append("")

    # ── 既存セレクタの存在確認 ──────────────────────────────────────────────
    lines.append("【現在 get_shop_name.py が使用しているセレクタの存在確認】")
    for sel in ["#loginId", "#loginPass", "#login_btn"]:
        el = page.query_selector(sel)
        lines.append(f"  {sel} : {'存在する ✓' if el else '見つからない ✗'}")
    lines.append("")

    return lines


def main() -> None:
    print(f"GH ログインフォーム調査を開始します: {GH_LOGIN_URL}")
    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=True,
            args=["--no-sandbox", "--disable-blink-features=AutomationControlled"],
        )
        context = browser.new_context(
            user_agent=(
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                "AppleWebKit/537.36 (KHTML, like Gecko) "
                "Chrome/124.0.0.0 Safari/537.36"
            ),
            locale="ja-JP",
            timezone_id="Asia/Tokyo",
        )
        page = context.new_page()

        try:
            page.goto(GH_LOGIN_URL, timeout=PAGE_TIMEOUT, wait_until="networkidle")
        except Exception as e:
            print(f"ページ読み込みエラー（続行）: {e}")

        lines = collect_form_info(page)

        # スクリーンショット
        try:
            page.screenshot(path=str(PNG_OUT), full_page=True)
            print(f"スクリーンショット保存: {PNG_OUT}")
        except Exception as e:
            print(f"スクリーンショット保存失敗: {e}")

        browser.close()

    # テキスト出力
    TXT_OUT.write_text("\n".join(lines), encoding="utf-8")
    print(f"フォーム構造保存: {TXT_OUT}")
    print()
    # 標準出力にも表示
    print("\n".join(lines))


if __name__ == "__main__":
    main()
