#!/usr/bin/env python3
"""WIRES-X on Raspberry Pi 判定ツール

  wx-check env [--brief] [--quick]   環境チェック(どこが未設定か・何をすればよいか)
  wx-check log [ファイル] [--brief]  WIRES-X のログを解析して、落ちた原因の候補を出す(省略時は最新)
  wx-check test                      対話式の試験(起動〜ルーム接続〜送受信)を順に行い、原因を判定する
  wx-check report                    貼り付け用のレポートを作る(環境+最新の試験結果+ログ解析)
  wx-check netdebug                  ネットワークの確認(OFFLINE のままのとき)
  wx-check menu                      上をメニューから選ぶ
"""
import json
import os
import re
import select
import shutil
import signal
import subprocess
import sys
import time
from datetime import datetime
from pathlib import Path

VERSION = "0.3.4"
HOME = Path.home()
LAB = HOME / "wiresx-lab"
LOGS = LAB / "logs"
RESULTS = LAB / "results"
REPORTS = LAB / "reports"
PREFIX = Path(os.environ.get("WINEPREFIX", HOME / ".wine-wiresx"))
WINE_DIR = Path("/opt/wiresx-lab/wine/current")
CONF_FILE = Path("/etc/wiresx-lab.conf")

COLOR = sys.stdout.isatty()
def col(s, c):
    return f"\033[{c}m{s}\033[0m" if COLOR else s

ICON = {"OK": col("[OK]", 32), "WARN": col("[注意]", 33), "FAIL": col("[NG]", 31), "INFO": col("[--]", 2), "SKIP": col("[ - ]", 2)}


def load_conf():
    conf = {"COM_PORT": "COM3", "DEVICE_LINK": "/dev/wiresx", "WINE_VERSION": "?", "WX_LANG": "ja_JP.UTF-8",
            "COM_HRI": "COM4", "DEVICE_HRI": "/dev/wiresx-hri"}
    try:
        for line in CONF_FILE.read_text().splitlines():
            m = re.match(r'\s*([A-Z_]+)="?([^"#]*)"?', line)
            if m:
                conf[m.group(1)] = m.group(2).strip()
    except OSError:
        pass
    return conf


CONF = load_conf()


def run(cmd, timeout=20, env=None):
    """コマンドを実行して (終了コード, 出力) を返す。見つからなければ (127, '')"""
    try:
        p = subprocess.run(cmd, shell=isinstance(cmd, str), capture_output=True, text=True,
                           timeout=timeout, env=env, errors="replace")
        return p.returncode, (p.stdout + p.stderr).strip()
    except FileNotFoundError:
        return 127, ""
    except subprocess.TimeoutExpired:
        return 124, "(タイムアウト)"


def read_text(path):
    try:
        return Path(path).read_text(errors="replace")
    except OSError:
        return ""


# ====================================================================== 環境チェック
class Checker:
    def __init__(self):
        self.items = []

    def add(self, status, group, title, detail="", fix=""):
        self.items.append({"status": status, "group": group, "title": title, "detail": detail, "fix": fix})

    def count(self, status):
        return sum(1 for i in self.items if i["status"] == status)


def wine_reg_section(regfile, section):
    """Wine の .reg ファイルから [section] の値を辞書で返す(キー名は小文字で比較)"""
    text = read_text(regfile)
    want = "[" + section.lower().replace("\\", "\\\\") + "]"
    out, inside = {}, False
    for line in text.splitlines():
        if line.startswith("["):
            inside = line.split("]")[0].lower() + "]" == want
            continue
        if inside:
            m = re.match(r'"((?:[^"\\]|\\.)*)"="((?:[^"\\]|\\.)*)"', line)
            if m:
                out[m.group(1).replace("\\\\", "\\")] = m.group(2).replace("\\\\", "\\")
            elif line.startswith("@="):
                out["@"] = line[2:].strip('"')
    return out


def wine_reg_find_sections(regfile, pattern):
    text = read_text(regfile)
    return [m.group(1) for m in re.finditer(r"^\[([^\]]+)\]", text, re.M) if re.search(pattern, m.group(1), re.I)]


def usb_info_for_tty(tty):
    """/dev/ttyUSBn の USB 情報(VID, PID, ドライバ, 製品名)"""
    name = Path(tty).name
    dev = Path(f"/sys/class/tty/{name}/device")
    info = {"vid": "", "pid": "", "driver": "", "product": ""}
    try:
        info["driver"] = os.path.basename(os.readlink(dev / "driver"))
    except OSError:
        pass
    p = dev.resolve()
    for _ in range(6):
        if (p / "idVendor").exists():
            info["vid"] = read_text(p / "idVendor").strip().upper()
            info["pid"] = read_text(p / "idProduct").strip().upper()
            info["product"] = read_text(p / "product").strip()
            break
        p = p.parent
    return info


def prolific_devices():
    out = []
    for d in Path("/sys/bus/usb/devices").glob("*"):
        if read_text(d / "idVendor").strip().lower() == "067b":
            out.append((read_text(d / "idProduct").strip().upper(), read_text(d / "product").strip()))
    return out


def usb_has_vendor(vid):
    return any(read_text(d / "idVendor").strip().lower() == vid for d in Path("/sys/bus/usb/devices").glob("*"))


def hri200_present():
    return usb_has_vendor("26aa")


def port_users(target):
    users = []
    for fd in Path("/proc").glob("[0-9]*/fd/*"):
        try:
            if os.readlink(fd) == target:
                pid = fd.parts[2]
                users.append(f"{read_text(f'/proc/{pid}/comm').strip()}(pid {pid})")
        except OSError:
            continue
    return sorted(set(users))


def find_wiresx_exe():
    p = LAB / "wiresx.path"
    if p.exists() and Path(read_text(p).strip()).is_file():
        return read_text(p).strip()
    base = PREFIX / "drive_c"
    if base.exists():
        for f in base.rglob("*"):
            n = f.name.lower()
            if f.is_file() and n.endswith(".exe") and re.search(r"wires.?x", n) and not re.search(r"unins|setup|install|update|driver", n):
                return str(f)
    return ""


def check_env(quick=False):
    c = Checker()
    # --- システム
    arch = os.uname().machine
    c.add("OK" if arch == "aarch64" else "FAIL", "システム", f"アーキテクチャ: {arch}",
          fix="" if arch == "aarch64" else "64bit版の Raspberry Pi OS を使ってください")
    ps = os.sysconf("SC_PAGE_SIZE")
    c.add("OK" if ps == 4096 else "FAIL", "システム", f"ページサイズ: {ps}",
          fix="" if ps == 4096 else "config.txt に kernel=kernel8.img を追記して再起動(sudo ./install.sh が案内します)")
    model = read_text("/proc/device-tree/model").strip("\0\n ") or "不明"
    osname = re.search(r'PRETTY_NAME="([^"]+)"', read_text("/etc/os-release"))
    mem = int(re.search(r"MemTotal:\s+(\d+)", read_text("/proc/meminfo")).group(1)) // 1024
    c.add("INFO", "システム", f"{model} / {osname.group(1) if osname else '?'} / メモリ {mem}MB / カーネル {os.uname().release}")
    # --- エミュレーション
    box = shutil.which("box64")
    if box:
        rc, out = run(["box64", "--version"], 10)
        c.add("OK", "エミュレーション", "box64: " + (out.splitlines()[-1] if out else "?"))
        binfmt = any("box64" in p.name.lower() for p in Path("/proc/sys/fs/binfmt_misc").glob("*"))
        c.add("OK" if binfmt else "WARN", "エミュレーション", "binfmt 登録" + ("あり" if binfmt else "なし"),
              fix="" if binfmt else "sudo systemctl restart systemd-binfmt(wx-wine は box64 を明示するので必須ではありません)")
    else:
        c.add("FAIL", "エミュレーション", "box64 が見つかりません", fix="sudo ./install.sh --steps box64")
    if (WINE_DIR / "bin/wine").exists():
        ver = os.path.basename(os.path.realpath(WINE_DIR))
        if quick or not box:
            c.add("OK", "エミュレーション", f"Wine: {ver}(起動確認は省略)")
        else:
            rc, out = run(["/usr/local/bin/wx-wine", "--version"], 120, env={**os.environ, "WINEDEBUG": "-all"})
            c.add("OK" if rc == 0 and "wine" in out.lower() else "FAIL", "エミュレーション",
                  f"Wine: {ver} → {out.splitlines()[-1] if out else '応答なし'}",
                  fix="" if rc == 0 else "BOX64_LOG=1 wx-wine --version で詳細を確認")
    else:
        c.add("FAIL", "エミュレーション", "Wine が見つかりません", fix="sudo ./install.sh --steps wine")
    # --- 機器(HRI-200 / PDN)
    link = CONF.get("DEVICE_LINK", "/dev/wiresx")
    devs = prolific_devices()
    hri = hri200_present()
    if hri:
        check_hri(c)
    if devs:
        c.add("OK", "シリアル", "Prolific のケーブルを検出: " + ", ".join(f"PID {p} {n}" for p, n in devs))
    elif hri:
        c.add("INFO", "シリアル", "Prolific のケーブルはつながっていません(HRI-200 で使う場合は不要です)")
    else:
        c.add("FAIL", "シリアル", "無線機の機器が見つかりません(HRI-200 も Prolific のケーブルも USB に見えません)",
              fix="HRI-200 またはケーブル(SCU-20 / SCU-56 など)の抜き差し / lsusb で 26aa か 067b が出るか確認")
    target = os.path.realpath(link) if os.path.exists(link) else ""
    if target:
        u = usb_info_for_tty(target)
        c.add("OK", "シリアル", f"{link} → {target}(ドライバ {u['driver'] or '?'} / VID_{u['vid']}&PID_{u['pid']})")
        if u["driver"] and u["driver"] != "pl2303":
            c.add("WARN", "シリアル", f"ドライバが pl2303 ではありません: {u['driver']}")
        if os.access(target, os.R_OK | os.W_OK):
            c.add("OK", "シリアル", "ポートの読み書き権限あり")
        else:
            c.add("FAIL", "シリアル", "ポートの読み書き権限がありません", fix="dialout グループに入っているか確認し、ログインし直す")
        busy = [x for x in port_users(target)]
        c.add("WARN" if busy else "OK", "シリアル", "ポートを使用中: " + ", ".join(busy) if busy else "他のプログラムはポートを使っていません",
              fix="WIRES-X 以外が使っていたら終了する" if busy else "")
    elif devs:
        c.add("FAIL", "シリアル", f"{link} がありません",
              fix="sudo ./install.sh --steps serial を実行し、ケーブルを挿し直す")
    try:
        in_file = os.getlogin()
    except OSError:
        in_file = ""
    grp_line = [l for l in read_text("/etc/group").splitlines() if l.startswith("dialout:")]
    members = grp_line[0].split(":")[-1].split(",") if grp_line else []
    import pwd
    user = os.environ.get("USER") or in_file or pwd.getpwuid(os.getuid()).pw_name
    try:
        import grp
        in_session = grp.getgrnam("dialout").gr_gid in os.getgroups()
    except (KeyError, ImportError):
        in_session = False
    if in_session:
        c.add("OK", "シリアル", "dialout グループ: 有効")
    elif user in members:
        c.add("FAIL", "シリアル", "dialout グループに追加済みだが、まだ有効になっていません", fix="ログアウトしてログインし直す(または再起動)")
    else:
        c.add("FAIL", "シリアル", "dialout グループに入っていません", fix=f"sudo usermod -aG dialout {user} のあと、ログインし直す")
    rc, out = run(["systemctl", "is-active", "ModemManager"], 5)
    c.add("WARN" if out.strip() == "active" else "OK", "シリアル",
          "ModemManager: " + ("動作中(ポートを横取りする可能性)" if out.strip() == "active" else "停止"),
          fix="sudo systemctl disable --now ModemManager" if out.strip() == "active" else "")
    rc, out = run(["systemctl", "is-active", "brltty"], 5)
    if out.strip() == "active":
        c.add("WARN", "シリアル", "brltty が動作中(USB シリアルを掴むことがあります)", fix="sudo apt purge brltty")
    # --- Wine の設定
    sysreg, usrreg = PREFIX / "system.reg", PREFIX / "user.reg"
    com = CONF.get("COM_PORT", "COM3")
    if sysreg.exists():
        c.add("OK", "Wine設定", f"プレフィックス: {PREFIX}")
        ports = {k.upper(): v for k, v in wine_reg_section(sysreg, r"Software\Wine\Ports").items()}
        if ports.get(com.upper()) == link:
            c.add("OK", "Wine設定", f"{com} → {link}")
        else:
            c.add("FAIL", "Wine設定", f"{com} の割り当てがありません(現在: {ports or 'なし'})", fix="wx-prefix ports")
        dd = PREFIX / "dosdevices" / com.lower()
        if dd.is_symlink() and os.readlink(dd) == link:
            c.add("OK", "Wine設定", f"dosdevices/{com.lower()} → {link}")
        else:
            c.add("WARN", "Wine設定", f"dosdevices/{com.lower()} が {link} を指していません", fix="wx-prefix ports")
        secs = wine_reg_find_sections(sysreg, r"Enum\\\\USB\\\\VID_067B")
        inst = [s for s in secs if not s.lower().endswith("device parameters")]
        if inst:
            vals = wine_reg_section(sysreg, inst[0].replace("\\\\", "\\"))
            fname = vals.get("FriendlyName", "")
            c.add("OK" if fname.endswith(f"({com})") else "WARN", "Wine設定", f"ポート一覧(SetupAPI)の登録: {fname or '名前なし'}",
                  fix="" if fname.endswith(f"({com})") else "wx-prefix ports")
            m = re.search(r"VID_([0-9A-F]{4})&PID_([0-9A-F]{4})", inst[0], re.I)
            if m and target:
                u = usb_info_for_tty(target)
                if u["pid"] and m.group(2).upper() != u["pid"]:
                    c.add("WARN", "Wine設定", f"登録の PID {m.group(2)} と接続中のケーブル PID {u['pid']} が違います", fix="wx-prefix ports")
        else:
            c.add("FAIL", "Wine設定", "ポート一覧(SetupAPI)の登録がありません(初回起動で落ちる原因の候補)", fix="wx-prefix ports")
        hsecs = [s_ for s_ in wine_reg_find_sections(sysreg, r"Enum\\\\USB\\\\VID_26AA&PID_0002")
                 if not s_.lower().endswith("device parameters")]
        hcom = CONF.get("COM_HRI", "COM4")
        if hsecs:
            fname = wine_reg_section(sysreg, hsecs[0].replace("\\\\", "\\")).get("FriendlyName", "")
            c.add("OK", "Wine設定", f"HRI-200 のポート登録: {fname or '名前なし'}")
        else:
            c.add("FAIL" if hri else "INFO", "Wine設定", "HRI-200 のポート登録がありません", fix="wx-prefix ports")
        drv = wine_reg_section(usrreg, r"Software\Wine\Drivers").get("Audio", "")
        c.add("OK" if drv in ("pulse", "") else "INFO", "Wine設定", f"Wine の音声ドライバ: {drv or '自動'}")
    else:
        c.add("FAIL", "Wine設定", f"プレフィックスがありません: {PREFIX}", fix="wx-prefix init")
    check_wine_fixes(c)
    # --- 音声
    if hri:
        pass   # HRI-200 の音声は check_hri で確認済み。仮想デバイスは使わない
    elif shutil.which("pactl"):
        rc, _ = run(["pactl", "info"], 5)
        if rc == 0:
            _, sinks = run(["pactl", "list", "short", "sinks"], 5)
            _, srcs = run(["pactl", "list", "short", "sources"], 5)
            has_out = re.search(r"\swiresx_out\s", sinks + " ") is not None
            has_in = re.search(r"\swiresx_in\s", srcs + " ") is not None
            real_in = [l.split()[1] for l in srcs.splitlines() if len(l.split()) > 1 and not l.split()[1].endswith(".monitor")]
            c.add("OK" if has_out and has_in else "WARN", "音声",
                  f"仮想デバイス: 出力 {'●' if has_out else '○'} / 入力 {'●' if has_in else '○'}",
                  fix="" if has_out and has_in else "wx-audio on")
            _, ds = run(["pactl", "get-default-sink"], 5)
            _, dr = run(["pactl", "get-default-source"], 5)
            c.add("INFO", "音声", f"既定: 出力 {ds or '?'} / 入力 {dr or '?'} / 入力デバイス数 {len(real_in)}")
            if not real_in:
                c.add("WARN", "音声", "入力(録音)デバイスが1つもありません(WIRES-X が落ちる原因の候補)", fix="wx-audio on")
        else:
            c.add("WARN", "音声", "音声サーバーに接続できません(デスクトップにログインした状態で実行してください)")
    else:
        c.add("WARN", "音声", "pactl がありません", fix="sudo apt install pulseaudio-utils")
    # --- WIRES-X
    exe = find_wiresx_exe()
    c.add("OK" if exe else "WARN", "WIRES-X", f"実行ファイル: {exe}" if exe else "未導入",
          fix="" if exe else "デスクトップの「② WIRES-X を導入」(または wx-install-wiresx)")
    if exe:
        c.add("INFO", "WIRES-X", "QSL 画像を表示するには、WIRES-X の 設定 → 自局Node設定 の「QSL画像」にチェックを入れてください")
    # --- デスクトップ
    st = os.environ.get("XDG_SESSION_TYPE", "?")
    de = os.environ.get("XDG_CURRENT_DESKTOP", "?")
    c.add("OK" if st == "x11" else "INFO", "デスクトップ", f"セッション: {st} / {de}",
          fix="" if st == "x11" else "ログイン画面でセッションを Xfce にすると安定します")
    rc, out = run(["locale", "-a"], 5)
    jl = CONF.get("WX_LANG", "ja_JP.UTF-8").split(".")[0].lower()
    c.add("OK" if jl in out.lower() else "WARN", "デスクトップ", f"ロケール {CONF.get('WX_LANG')}: " + ("あり" if jl in out.lower() else "なし"),
          fix="" if jl in out.lower() else "sudo ./install.sh --steps packages")
    # --- 最新ログ
    last = latest_log()
    if last:
        a = analyze_log(last)
        c.add("INFO", "最新の実行", f"{last.name}: {a['summary']}")
    return c


def check_hri(c):
    dev = CONF.get("DEVICE_HRI", "/dev/wiresx-hri")
    c.add("OK", "HRI-200", "HRI-200 を USB で検出(26aa)")
    if os.path.exists(dev):
        t = os.path.realpath(dev)
        ok = os.access(t, os.R_OK | os.W_OK)
        c.add("OK" if ok else "FAIL", "HRI-200", f"通信ポート {dev} → {t}" + ("" if ok else "(読み書き権限なし)"),
              fix="" if ok else "dialout グループに入っているか確認し、ログインし直す")
    else:
        c.add("FAIL", "HRI-200", f"通信ポート {dev} がありません", fix="sudo ./install.sh --steps hri200 のあと HRI-200 を挿し直す")
    hids = []
    for h in Path("/sys/class/hidraw").glob("hidraw*"):
        if "26AA" in read_text(h / "device/uevent").upper():
            hids.append(Path("/dev") / h.name)
    if hids:
        bad = [str(h) for h in hids if not os.access(h, os.R_OK | os.W_OK)]
        c.add("FAIL" if bad else "OK", "HRI-200",
              "HID: " + ", ".join(str(h) for h in hids) + (f"(読み取り不可: {', '.join(bad)})" if bad else "(読み取り可)"),
              fix="sudo ./install.sh --steps hri200 のあと HRI-200 を挿し直す" if bad else "")
    else:
        c.add("WARN", "HRI-200", "HRI-200 の HID が見えません(WIRES-X が HRI-200 を検出できない原因になります)")
    if shutil.which("pactl") and run(["pactl", "info"], 5)[0] == 0:
        _, out = run(["pactl", "list", "sinks"], 5)
        _, out2 = run(["pactl", "list", "sources"], 5)
        want = "HRI-200 A(CH1) USB Audio codec"
        okname = f"Description: {want}" in out and f"Description: {want}" in out2
        c.add("OK" if okname else "FAIL", "HRI-200", f"音声デバイス名「{want}」: " + ("一致" if okname else "不一致"),
              fix="" if okname else "sudo ./install.sh --steps hri200 のあと、ログインし直す(WirePlumber の名前合わせ)")
        _, ds = run(["pactl", "get-default-sink"], 5)
        if "wiresx_" in ds:
            c.add("WARN", "HRI-200", "PDN 用の仮想音声デバイスが既定になっています", fix="wx-audio off")
    else:
        c.add("WARN", "HRI-200", "音声サーバーに接続できません(デスクトップにログインした状態で実行してください)")


def check_wine_fixes(c):
    import hashlib
    fx = Path("/opt/wiresx-lab/share/wine-fixes")
    lib = WINE_DIR / "lib/wine/i386-windows"
    if not fx.exists():
        return
    names = ["wininet.dll", "msgsm32.acm", "comctl32.dll"]
    md5 = lambda p: hashlib.md5(p.read_bytes()).hexdigest() if p.exists() else ""
    same = [n for n in names if md5(fx / n) and md5(fx / n) == md5(lib / n)]
    if len(same) == len(names):
        c.add("OK", "Wine設定", "WIRES-X 用の Wine 修正版: 導入済み(wininet / msgsm32 / comctl32)")
    else:
        miss = [n for n in names if n not in same]
        c.add("FAIL", "Wine設定", "WIRES-X 用の Wine 修正版が入っていません: " + ", ".join(miss),
              detail="入っていないと OFFLINE のまま・受信した瞬間に落ちる・一覧に A が並ぶ、が起きます",
              fix="sudo ./install.sh --steps wine(Wine 10.0 のときだけ入ります)")


def cmd_netdebug():
    print(col(f"== WIRES-X ネットワーク確認 v{VERSION}", 1))
    host = os.uname().nodename
    rc, out = run(["getent", "hosts", host], 5)
    print(f"[ホスト名] {host} → {out or '解決できません'}")
    rc, out = run(["ip", "-4", "route", "show", "default"], 5)
    print(f"[既定の経路] {out or 'なし(ネットワークにつながっていません)'}")
    rc, out = run(["ip", "-brief", "address"], 5)
    print("[アダプター]\n  " + "\n  ".join(out.splitlines()))
    rc, out = run(["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "8",
                   "http://180.42.3.130/sv/UpdateInfoX_New.bin"], 15)
    print(f"[WIRES-X 更新情報サーバー] HTTP {out or '応答なし'}" + ("(正常)" if out == "200" else ""))
    rc, out = run("ss -lunp 2>/dev/null | grep -E ':461[0-9]{2}' || true", 5)
    print("[WIRES-X の UDP ポート(461xx)]\n  " + ("\n  ".join(out.splitlines()) if out else "待ち受けなし(WIRES-X が起動していない?)"))
    if shutil.which("upnpc"):
        rc, out = run(["upnpc", "-s"], 15)
        ext = re.search(r"ExternalIPAddress = (\S+)", out)
        print("[ルーターの UPnP] " + (f"利用可(外部 IP {ext.group(1)})" if ext else "見つかりません(ルーター側で UPnP が無効の可能性)"))
    lib = WINE_DIR / "lib/wine/i386-windows/wininet.dll"
    fx = Path("/opt/wiresx-lab/share/wine-fixes/wininet.dll")
    if fx.exists():
        same = lib.exists() and lib.read_bytes() == fx.read_bytes()
        print("[Wine の wininet 修正版] " + ("導入済み" if same else "未導入(OFFLINE のままになります: sudo ./install.sh --steps wine)"))
    _, top = run("ps -eo pcpu,comm | grep -i 'wires-x' | head -1", 5)
    if top:
        print(f"[WIRES-X の CPU 使用率] {top.split()[0]}%" + ("(高い: 更新情報の確認でループしている可能性)" if float(top.split()[0] or 0) > 90 else ""))
    print("\nOFFLINE のままのときは、この結果を共有してください")
    return 0


def print_env(c, brief=False):
    groups = []
    for i in c.items:
        if i["group"] not in groups:
            groups.append(i["group"])
    print(col(f"== WIRES-X 環境チェック v{VERSION}  {datetime.now():%Y-%m-%d %H:%M}", 1))
    for g in groups:
        rows = [i for i in c.items if i["group"] == g]
        if brief and all(r["status"] in ("OK", "INFO") for r in rows):
            print(f"  {ICON['OK']} {g}")
            continue
        print(col(f"[{g}]", 1))
        for r in rows:
            if brief and r["status"] in ("OK", "INFO"):
                continue
            print(f"  {ICON[r['status']]} {r['title']}")
            if r["detail"]:
                print(f"      {r['detail']}")
            if r["fix"] and r["status"] in ("FAIL", "WARN"):
                print(col(f"      → {r['fix']}", 36))
    f, w = c.count("FAIL"), c.count("WARN")
    verdict = col("準備OK", 32) if f == 0 else col(f"未完了 {f} 件", 31)
    print(f"\n判定: {verdict}(注意 {w} 件)")
    return f


# ====================================================================== ログ解析
CATS = {
    "audio": "音声デバイス",
    "network": "ネットワーク",
    "serial": "シリアル通信",
    "devenum": "ポート・デバイスの列挙",
    "emulator": "box64(エミュレーション)",
    "dotnet": ".NET(Mono)",
    "gui": "画面描画・部品",
    "unknown": "不明",
}
HINTS = {
    "audio": "wx-audio status で仮想デバイスを確認 → wx-check test の『音声あり/なし』比較で確定できます",
    "network": "ログにある DLL/関数名が手掛かりです。UPnP を使う設定があれば切る・ルーターで手動ポート開放にする",
    "serial": "wiresx --debug deep --strace で、落ちる直前のシリアル操作を記録してください",
    "devenum": "wx-prefix ports でポート一覧の登録をやり直してください",
    "emulator": "wiresx --profile strongmem1(→2→3)で再現するか確認。直ればそのプロファイルを既定にします",
    "dotnet": "wx-prefix mono で wine-mono を導入してください",
    "gui": "Windows 純正の DLL への置き換えが必要な可能性があります(DLL名を控えてください)",
    "unknown": "wiresx --debug deep で詳しいログを取り、wx-check report を共有してください",
}
DLL_CAT = {}
for _c, _dlls in {
    "audio": "winmm mmdevapi winepulse winealsa dsound wdmaud msacm32 ksuser avrt audioses quartz dmusic",
    "network": "ws2_32 wsock32 mswsock iphlpapi wininet winhttp hnetcfg upnp dnsapi netapi32 nsi urlmon httpapi rasapi32 sensapi",
    "devenum": "setupapi cfgmgr32 newdev wbemprox wmi hid",
    "dotnet": "mscoree clr mscorwks mscorlib",
    "gui": "user32 comctl32 gdiplus riched20 riched32 uxtheme gdi32 msftedit oleaut32 shell32 mfc42 mfc140 mfc100",
}.items():
    for _d in _dlls.split():
        DLL_CAT[_d] = _c
COMM_FUNCS = re.compile(r"\b(SetCommState|GetCommState|WaitCommEvent|SetCommTimeouts|GetCommTimeouts|PurgeComm|ClearCommError|"
                        r"EscapeCommFunction|SetCommMask|GetCommModemStatus|SetupComm|GetOverlappedResult|TransmitCommChar|BuildCommDCB)")


def dll_category(name):
    n = name.lower().split("\\")[-1].split("/")[-1]
    n = re.sub(r"\.(dll|drv|sys|exe|so)$", "", n)
    return DLL_CAT.get(n, ""), n


def latest_log():
    logs = sorted(LOGS.glob("run_*.log"), key=lambda p: p.stat().st_mtime) if LOGS.exists() else []
    return logs[-1] if logs else None


def read_meta(log):
    meta = {}
    for line in read_text(Path(str(log)[:-4] + ".meta")).splitlines():
        if "=" in line:
            k, v = line.split("=", 1)
            meta[k] = v
    return meta


def analyze_log(path):
    text = read_text(path)
    lines = text.splitlines()
    meta = read_meta(path)
    score = {k: 0 for k in CATS}
    ev = []        # 根拠になった行
    unimpl = []
    crash_idx = None

    def hit(cat, pts, line, note=""):
        score[cat] += pts
        if len(ev) < 14:
            ev.append((CATS[cat], (note + " " if note else "") + line.strip()[:200]))

    loaded = []    # (行番号, DLL名)
    last_comm = None
    for i, line in enumerate(lines):
        m = re.search(r"Loaded L\"([^\"]+)\"", line)
        if m:
            loaded.append((i, dll_category(m.group(1))[1]))
        if "trace:comm" in line or "trace:serial" in line or COMM_FUNCS.search(line):
            last_comm = (i, line)
        m = re.search(r"to unimplemented function ([\w.]+)\.(\w+)", line)
        if m:
            cat, n = dll_category(m.group(1))
            if not cat and COMM_FUNCS.search(m.group(2)):
                cat = "serial"
            unimpl.append(f"{m.group(1)}.{m.group(2)}")
            hit(cat or "unknown", 6, line, "未実装の関数:")
            crash_idx = crash_idx if crash_idx is not None else i
        if re.search(r"Unhandled (exception|page fault|illegal instruction|stack overflow)", line) or \
           re.search(r"wine: Unhandled", line):
            crash_idx = crash_idx if crash_idx is not None else i
            ev.append(("例外", line.strip()[:200]))
        if re.search(r"(?i)unimplemented opcode|SIGILL|box64.*fatal", line):
            hit("emulator", 5, line)
            crash_idx = crash_idx if crash_idx is not None else i
        elif re.search(r"(?i)SIGSEGV with Access error|\[box64\].*error", line):
            # Wine は例外処理で SIGSEGV を普通に使うので、単独では弱い根拠にとどめる
            if score["emulator"] < 2:
                hit("emulator", 1, line)
        m = re.match(r"\s*=?>?\s*\d+\s+0x[0-9a-f]+\s+in\s+(\S+)", line)
        if m and crash_idx is not None and i - crash_idx < 40:
            cat, n = dll_category(m.group(1))
            if cat:
                hit(cat, 4, line, "落ちた場所:")
        if re.search(r"err:(winmm|mmdevapi|pulse|wave|dsound|alsa)", line) or \
           re.search(r"(?i)(no (sound|audio) (devices?|card)|waveInOpen.*(fail|err)|Unable to connect to pulse|pa_context_connect)", line):
            hit("audio", 2 if score["audio"] < 6 else 0, line)
        if re.search(r"err:(winsock|iphlpapi|wininet|winhttp|hnetcfg|upnp)", line):
            hit("network", 1 if score["network"] < 3 else 0, line)
        if re.search(r"err:(comm|serial)", line):
            hit("serial", 2 if score["serial"] < 6 else 0, line)
        if re.search(r"err:(setupapi|cfgmgr32|wbemprox)", line):
            hit("devenum", 1 if score["devenum"] < 3 else 0, line)
        if re.search(r"(?i)mscoree|wine mono is not installed|CLR(Create|Runtime)", line) and "err:" in line:
            hit("dotnet", 4, line)

    # 落ちる直前に読み込まれた DLL / シリアル操作
    near_dlls = []
    if crash_idx is not None:
        near_dlls = [n for i, n in loaded if crash_idx - 400 < i < crash_idx][-6:]
        for n in near_dlls[-3:]:
            cat, _ = dll_category(n)
            if cat:
                score[cat] += 1
        if last_comm and crash_idx - last_comm[0] < 30:
            score["serial"] += 2
            ev.append((CATS["serial"], "落ちる直前のシリアル操作: " + last_comm[1].strip()[:160]))

    rc = meta.get("exit_code")
    crashed = crash_idx is not None or (rc not in (None, "", "0"))
    ranked = sorted(((v, k) for k, v in score.items() if v > 0), reverse=True)
    if crashed and not ranked:
        ranked = [(1, "unknown")]
    if not crashed:
        summary = "異常終了の記録なし" + (f"(終了コード {rc})" if rc else "")
    else:
        summary = "落ちた形跡あり → 候補: " + "、".join(CATS[k] for _, k in ranked[:3])
    return {"file": str(path), "crashed": crashed, "exit_code": rc, "meta": meta, "ranked": ranked,
            "evidence": ev, "unimplemented": sorted(set(unimpl)), "near_dlls": near_dlls, "summary": summary}


def print_analysis(a, brief=False):
    print(col(f"== ログ解析: {Path(a['file']).name}", 1))
    m = a["meta"]
    if m:
        print(f"   プロファイル {m.get('profile', '?')} / 音声 {m.get('audio', '?')} / 終了コード {m.get('exit_code', '?')} / {m.get('seconds', '?')}秒")
    print(f"   {a['summary']}")
    if not a["crashed"]:
        return
    if a["unimplemented"]:
        print(col("   未実装の関数: " + ", ".join(a["unimplemented"]), 33))
    for pts, k in a["ranked"][: (1 if brief else 3)]:
        print(f"   {ICON['WARN']} {CATS[k]}(根拠の強さ {pts})")
        print(col(f"      → {HINTS[k]}", 36))
    if brief:
        print("   (詳しく: wx-check log)")
        return
    if a["near_dlls"]:
        print("   落ちる直前に読み込まれたDLL: " + ", ".join(a["near_dlls"]))
    if a["evidence"]:
        print("   根拠になった行:")
        for cat, line in a["evidence"]:
            print(f"     [{cat}] {line}")


# ====================================================================== 対話式の試験
STEPS = [
    ("startup", "起動", "WIRES-X のメイン画面が表示されましたか?"),
    ("radio", "無線機の認識", "無線機の情報(機種・ID など)が画面に表示されていますか?"),
    ("tx_idle", "未接続で送信", "ルームに接続していない状態で、無線機の PTT を 3 秒押して離してください。落ちずに動いていますか?"),
    ("connect", "ルーム接続", "ルーム(またはノード)に接続してください。接続できましたか?"),
    ("rx", "受信", "接続先の音声を受信するまで待ってください。受信中・受信後も落ちていませんか?"),
    ("tx_room", "接続中に送信", "接続したまま PTT を 3 秒押して離してください。落ちていませんか?"),
    ("exit", "終了", "WIRES-X を普通に終了してください(終了を自動で検出します)"),
]
NEEDS = {"rx": "connect", "tx_room": "connect", "radio": "startup", "tx_idle": "startup", "connect": "startup"}
MARK = {"ok": col("[OK]", 32), "crash": col("[落]", 31), "error": col("[エラー]", 33), "skip": col("[-]", 2), "na": col("[未]", 2), "hang": col("[固]", 31)}
TRIAL_PLAN_FAIL = [("strongmem1", "on"), ("strongmem2", "on"), ("strongmem3", "on")]


def ask(prompt, choices, proc=None):
    """選択肢を聞く。proc を渡すと、回答待ちの間にプロセスが落ちたら 'crash' を返す"""
    keys = "/".join(f"{k}={v}" for k, v in choices.items())
    print(f"\n{col('?', 36)} {prompt}\n   [{keys}] > ", end="", flush=True)
    while True:
        if proc is not None and proc.poll() is not None:
            print(col("\n   (WIRES-X の終了を検出しました)", 33))
            return "crash"
        r, _, _ = select.select([sys.stdin], [], [], 0.5)
        if r:
            raw = sys.stdin.readline()
            if raw == "":
                raise KeyboardInterrupt
            a = raw.strip().lower()
            if a == "" and "" in choices:
                return ""
            if a in choices:
                return a
            print(f"   [{keys}] > ", end="", flush=True)


def launch(profile, audio, tag):
    log_before = set(LOGS.glob("run_*.log")) if LOGS.exists() else set()
    proc = subprocess.Popen(["/usr/local/bin/wiresx", "--wait", "--debug", "diag", "--profile", profile, "--audio", audio, "--tag", tag],
                            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
    for _ in range(40):
        new = set(LOGS.glob("run_*.log")) - log_before
        if new:
            return proc, sorted(new)[-1]
        time.sleep(0.25)
    return proc, None


def stop(proc):
    if proc.poll() is None:
        try:
            os.killpg(proc.pid, signal.SIGTERM)
            proc.wait(10)
        except (ProcessLookupError, subprocess.TimeoutExpired):
            try:
                os.killpg(proc.pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
    run(["/usr/local/bin/wx-wineserver", "-k"], 15)
    time.sleep(2)


def ask_step(key, q, proc):
    if key == "startup":
        a = ask(q, {"o": "表示された", "x": "落ちた", "h": "固まった・表示されない"}, proc)
    elif key == "rx":
        a = ask(q, {"o": "落ちない", "x": "落ちた", "e": "エラー表示(落ちない)", "s": "受信がなくスキップ"}, proc)
    else:
        a = ask(q, {"o": "はい・問題なし", "x": "落ちた", "e": "エラー表示(落ちない)"}, proc)
    return {"o": "ok", "x": "crash", "e": "error", "s": "skip", "h": "hang", "crash": "crash"}[a]


def run_trial(name, profile, audio):
    print(col(f"\n== 試験 {name}: プロファイル {profile} / 仮想音声 {'あり' if audio == 'on' else 'なし'} ==", 1))
    titles = {k: t for k, t, _ in STEPS}
    res = {k: "na" for k, _, _ in STEPS}
    logs = []
    idx = 0
    while idx < len(STEPS):
        proc, log = launch(profile, audio, name)
        if log:
            logs.append(str(log))
        print(f"   起動しました(ログ: {log.name if log else '取得中'})。画面が出るまで 1〜2 分かかることがあります")
        if idx > 0:   # 落ちたあとに起動し直した場合は、画面が出たことだけ確かめて続きから
            if ask("起動し直しました。メイン画面が表示されたら o を入力してください",
                   {"o": "表示された", "x": "落ちた"}, proc) != "o":
                print(col("   → 起動し直しても落ちました。残りは未確認にします", 31))
                stop(proc)
                break
        crashed = None
        while idx < len(STEPS):
            key, title, q = STEPS[idx]
            dep = NEEDS.get(key)
            if dep and res.get(dep) not in ("ok", "error"):
                idx += 1           # 前提の項目が失敗しているので確認できない(未確認のまま)
                continue
            if key == "exit":
                print(f"\n{col('?', 36)} {q}")
                try:
                    proc.wait(180)
                    res[key] = "ok"
                except subprocess.TimeoutExpired:
                    res[key] = "hang"
                idx += 1
                break
            res[key] = ask_step(key, q, proc)
            idx += 1
            if res[key] in ("crash", "hang"):
                crashed = key
                break
        stop(proc)
        if not crashed:
            break
        print(col(f"   → 「{titles[crashed]}」で{'落ちました' if res[crashed] == 'crash' else '固まりました'}", 31))
        if crashed == "startup":
            break
        rest = [k for k, _, _ in STEPS[idx:] if k != "exit" and res.get(NEEDS.get(k, "startup")) in ("ok", "error")]
        if not rest:
            break
        if ask("WIRES-X を起動し直して、残りの確認(" + "・".join(titles[k] for k in rest) + ")に進みますか?",
               {"y": "はい", "n": "いいえ"}) != "y":
            break
    analyses = [analyze_log(l) for l in logs]
    passed = all(res[k] in ("ok", "skip") for k in ("startup", "radio", "tx_idle", "connect", "rx", "tx_room"))
    print("   結果: " + "  ".join(f"{t}{MARK[res[k]]}" for k, t, _ in STEPS))
    for a in analyses:
        if a["crashed"]:
            print_analysis(a, brief=True)
    return {"name": name, "profile": profile, "audio": audio, "steps": res, "passed": passed, "logs": logs,
            "analyses": [{k: a[k] for k in ("file", "crashed", "summary", "ranked", "unimplemented", "near_dlls", "evidence")}
                         for a in analyses]}


def verdict(trials, first_run):
    """試験結果から原因を判定する"""
    out = []
    by = {(t["profile"], t["audio"]): t for t in trials}
    base = by.get(("standard", "on"))
    noaudio = by.get(("standard", "off"))
    fixed_by = [t for t in trials if t["profile"] != "standard" and t["passed"]]
    if base and base["passed"]:
        if noaudio and not noaudio["passed"]:
            out.append(("確定", "音声デバイス",
                        "仮想音声デバイスがあると全項目OK、外すと落ちる → 原因は録音・再生デバイスの不在です。イメージに wx-audio を組み込めば解決します"))
        elif noaudio and noaudio["passed"]:
            out.append(("確定", "現環境で解決済み", "音声デバイスの有無に関係なく全項目OKでした(以前の問題は今回の設定で解消)"))
        else:
            out.append(("OK", "全項目OK", "標準プロファイルですべて動きました"))
    elif fixed_by:
        t = fixed_by[0]
        out.append(("確定", "box64(メモリ順序)",
                    f"標準では落ち、プロファイル {t['profile']} では全項目OK → box64 の設定で解決します。"
                    f"既定にするには: echo {t['profile']} > ~/wiresx-lab/default-profile"))
    elif base:
        # 落ちた場所とログから推定
        failed = [k for k, v in base["steps"].items() if v in ("crash", "hang")]
        scores = {}
        for t in trials:
            for a in t["analyses"]:
                for pts, k in a["ranked"]:
                    scores[k] = scores.get(k, 0) + pts
        unimpl = sorted({u for t in trials for a in t["analyses"] for u in a["unimplemented"]})
        where = "、".join(dict((k, t) for k, t, _ in STEPS)[k] for k in failed) or "不明"
        if base["steps"]["startup"] == "crash" and first_run:
            scores["devenum"] = scores.get("devenum", 0) + 3
        if "connect" in failed and base["steps"]["tx_idle"] == "ok":
            scores["network"] = scores.get("network", 0) + 2
        if "tx_idle" in failed:
            scores["serial"] = scores.get("serial", 0) + 2
        if "rx" in failed or "tx_room" in failed:
            scores["audio"] = scores.get("audio", 0) + 1
            scores["serial"] = scores.get("serial", 0) + 1
        ranked = sorted(((v, k) for k, v in scores.items()), reverse=True)
        msg = f"落ちた場所: {where}。box64 の設定変更では直りませんでした。"
        if unimpl:
            msg += " Wine の未実装関数: " + ", ".join(unimpl)
        out.append(("推定", "、".join(CATS[k] for _, k in ranked[:2]) or "不明", msg))
        for _, k in ranked[:2]:
            out.append(("次の手", CATS[k], HINTS[k]))
    return out


def cmd_test():
    if not sys.stdin.isatty():
        print("対話式の試験は端末から実行してください")
        return 2
    print(col(f"== WIRES-X 試験 v{VERSION}", 1))
    print("  起動 → 無線機の認識 → 未接続で送信 → ルーム接続 → 受信 → 接続中に送信 → 終了 の順に確認します。")
    print("  落ちたら自動で検出し、ログを解析します。無線機は PDN モードにして、ケーブルを接続しておいてください。")
    print(col("  ※ 送信の確認では実際に電波が出ます。免許の範囲内で、周波数が空いていることを確かめて行ってください。", 33))
    c = check_env(quick=True)
    fails = [i for i in c.items if i["status"] == "FAIL"]
    if fails:
        print(col("\n環境チェックで未完了の項目があります:", 31))
        for i in fails:
            print(f"  {ICON['FAIL']} {i['title']}  → {i['fix']}")
        if ask("このまま試験を続けますか?", {"y": "はい", "n": "いいえ"}) != "y":
            return 1
    first_run = ask("WIRES-X をこの環境で起動するのは初めてですか(設定ファイルなし)?", {"y": "はい", "n": "いいえ"}) == "y"
    trials = [run_trial("T1", "standard", "on")]
    if trials[0]["passed"]:
        if ask("全項目OKでした。仮想音声デバイスを外した状態でも試して、原因が音声だったか確定させますか?(推奨)",
               {"y": "はい", "n": "いいえ"}) == "y":
            trials.append(run_trial("T2", "standard", "off"))
    elif trials[0]["steps"]["startup"] in ("crash", "hang") and first_run:
        print(col("\n初回起動で落ちました。ポート一覧の登録をやり直してから、もう一度試します。", 33))
        run(["/usr/local/bin/wx-prefix", "ports"], 120)
        trials.append(run_trial("T1b", "standard", "on"))
    if not any(t["passed"] for t in trials):
        if ask("box64 の設定(メモリ順序を厳密にする)を変えて試しますか?(推奨)", {"y": "はい", "n": "いいえ"}) == "y":
            for n, (p, a) in enumerate(TRIAL_PLAN_FAIL, start=3):
                t = run_trial(f"T{n}", p, a)
                trials.append(t)
                if t["passed"]:
                    break
            else:
                if ask("dynarec を切った最も遅いモードでも試しますか?(起動に数分かかります)", {"y": "はい", "n": "いいえ"}) == "y":
                    trials.append(run_trial("T6", "nodynarec", "on"))
    v = verdict(trials, first_run)
    print(col("\n== 判定 ==", 1))
    for kind, title, msg in v:
        print(f"  [{kind}] {col(title, 1)}\n      {msg}")
    RESULTS.mkdir(parents=True, exist_ok=True)
    rf = RESULTS / f"test_{datetime.now():%Y%m%d_%H%M%S}.json"
    rf.write_text(json.dumps({"version": VERSION, "at": datetime.now().isoformat(timespec="seconds"),
                              "first_run": first_run, "trials": trials, "verdict": v}, ensure_ascii=False, indent=1))
    print(f"\n結果を保存しました: {rf}")
    print("共有するときは wx-check report の BEGIN〜END を貼ってください")
    return 0


# ====================================================================== レポート
def cmd_report():
    c = check_env(quick=False)
    lines = [f"===== WXLAB REPORT BEGIN v{VERSION} {datetime.now():%Y-%m-%d %H:%M} ====="]
    lines.append(f"conf: COM={CONF.get('COM_PORT')} device={CONF.get('DEVICE_LINK')} wine={CONF.get('WINE_VERSION')}{CONF.get('WINE_FLAVOR', '')}")
    for i in c.items:
        lines.append(f"[{i['status']}] {i['group']}: {i['title']}" + (f" → {i['fix']}" if i["fix"] and i["status"] in ("FAIL", "WARN") else ""))
    res = sorted(RESULTS.glob("test_*.json")) if RESULTS.exists() else []
    if res:
        d = json.loads(read_text(res[-1]))
        lines.append(f"--- 試験 {res[-1].name}(初回起動: {d.get('first_run')})")
        for t in d["trials"]:
            lines.append(f"{t['name']} {t['profile']}/audio-{t['audio']}: " + " ".join(f"{k}={v}" for k, v in t["steps"].items()))
            for a in t["analyses"]:
                if a["crashed"]:
                    lines.append(f"  log {Path(a['file']).name}: {a['summary']}")
                    if a["unimplemented"]:
                        lines.append("  unimplemented: " + ", ".join(a["unimplemented"]))
                    if a["near_dlls"]:
                        lines.append("  near_dlls: " + ", ".join(a["near_dlls"]))
                    for cat, l in a["evidence"][:8]:
                        lines.append(f"  [{cat}] {l}")
        for kind, title, msg in d["verdict"]:
            lines.append(f"判定[{kind}] {title}: {msg}")
    else:
        last = latest_log()
        if last:
            a = analyze_log(last)
            lines.append(f"--- 最新ログ {last.name}: {a['summary']}")
            for cat, l in a["evidence"][:10]:
                lines.append(f"  [{cat}] {l}")
            tail = read_text(last).splitlines()[-40:]
            lines.append("--- ログ末尾40行")
            lines += ["  " + l[:220] for l in tail]
    lines.append("===== WXLAB REPORT END =====")
    text = "\n".join(lines)
    print(text)
    REPORTS.mkdir(parents=True, exist_ok=True)
    f = REPORTS / f"report_{datetime.now():%Y%m%d_%H%M%S}.txt"
    f.write_text(text + "\n")
    print(f"\n(保存: {f})")
    return 0


def cmd_menu():
    while True:
        print(col("\n== WIRES-X 判定ツール", 1))
        print("  1) 環境チェック\n  2) 試験(起動〜送受信)\n  3) 最新ログの解析\n  4) 共有用レポート\n  5) ネットワーク確認(OFFLINE のとき)\n  q) 終了")
        a = input("> ").strip().lower()
        if a == "1":
            print_env(check_env())
        elif a == "2":
            cmd_test()
        elif a == "3":
            last = latest_log()
            print_analysis(analyze_log(last)) if last else print("ログがまだありません")
        elif a == "4":
            cmd_report()
        elif a == "5":
            cmd_netdebug()
        elif a in ("q", ""):
            return 0


def main(argv):
    cmd = argv[1] if len(argv) > 1 else "env"
    opts = set(a for a in argv[2:] if a.startswith("--"))
    args = [a for a in argv[2:] if not a.startswith("--")]
    LOGS.mkdir(parents=True, exist_ok=True)
    if cmd == "env":
        f = print_env(check_env(quick="--quick" in opts), brief="--brief" in opts)
        return 1 if f else 0
    if cmd == "log":
        p = Path(args[0]) if args else latest_log()
        if not p or not p.exists():
            print("解析するログがありません")
            return 1
        a = analyze_log(p)
        print_analysis(a, brief="--brief" in opts)
        return 0
    if cmd == "test":
        return cmd_test()
    if cmd == "report":
        return cmd_report()
    if cmd == "netdebug":
        return cmd_netdebug()
    if cmd == "menu":
        return cmd_menu()
    if cmd in ("-h", "--help", "help"):
        print(__doc__)
        return 0
    if cmd in ("--version", "version"):
        print(VERSION)
        return 0
    print(__doc__)
    return 2


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv))
    except KeyboardInterrupt:
        print("\n中断しました")
        sys.exit(130)
