#!/usr/bin/env python3
"""Run a command and create a portable execution report (HTML, Markdown, or both)."""
from __future__ import annotations

import argparse
from datetime import datetime
import fnmatch
import hashlib
import html
import importlib.metadata
import json
import locale
import os
from pathlib import Path
import platform
import re
import shlex
import shutil
import signal
import subprocess
import sys
import threading
import time
from urllib.parse import quote


DEFAULT_IGNORE = ".git,__pycache__,venv,.venv,.mypy_cache,.pytest_cache,*.pyc,*.pyo,*.tmp,*.bak,*.swp"
DEFAULT_LOG_EXTS = ".log,.out,.txt"
DEFAULT_ERROR_RE = r"\b(error|exception|traceback|failed|failure|not found|permission denied|overflow|underflow)\b"
DEFAULT_WARNING_RE = r"\b(warning|warn|deprecated|convergence|ill-conditioned)\b"
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp"}


def now_iso() -> str:
    return datetime.now().astimezone().isoformat(timespec="seconds")


def parse_csv(text: str) -> list[str]:
    return [part.strip() for part in text.split(",") if part.strip()]


def ignored(rel: str, patterns: list[str]) -> bool:
    parts = rel.split("/")
    return any(fnmatch.fnmatch(rel, p) or any(fnmatch.fnmatch(part, p) for part in parts)
               for p in patterns)


def snapshot(root: Path, excluded: Path | None, patterns: list[str], hash_mode: str,
             hash_names: set[str] | None = None):
    """Return relpath -> (size, mtime_ns, sha256-or-None), plus read errors."""
    records: dict[str, tuple[int, int, str | None]] = {}
    errors: list[str] = []
    for base, dirs, names in os.walk(root, followlinks=False):
        base_path = Path(base)
        dirs[:] = sorted(d for d in dirs if not (base_path / d).is_symlink()
                         and (base_path / d).resolve() != excluded
                         and not ignored((base_path / d).relative_to(root).as_posix(), patterns))
        for name in sorted(names):
            path = base_path / name
            if path.is_symlink():
                continue
            rel = path.relative_to(root).as_posix()
            if ignored(rel, patterns):
                continue
            try:
                st = path.stat()
                if not path.is_file():
                    continue
                digest = None
                if hash_mode == "all" or (hash_names is not None and rel in hash_names):
                    digest = sha256(path)
                records[rel] = (st.st_size, st.st_mtime_ns, digest)
            except OSError as exc:
                errors.append(f"{rel}: {exc}")
    return records, errors


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def compare(before, after, root: Path, hash_mode: str):
    created = sorted(after.keys() - before.keys())
    deleted = sorted(before.keys() - after.keys())
    modified = []
    for name in sorted(before.keys() & after.keys()):
        old, new = before[name], after[name]
        changed_stat = old[:2] != new[:2]
        different = changed_stat
        if hash_mode == "all":
            # Hashes were recorded in both snapshots.
            different = different or old[2] != new[2]
        elif hash_mode == "changed" and changed_stat and old[2] is not None and new[2] is not None:
            # Optimized mode hashes metadata candidates only and can miss a
            # content change that preserves both size and modification time.
            different = old[2] != new[2]
        if different:
            modified.append(name)
    return created, modified, deleted


def command_environment() -> dict:
    """Collect useful host/runtime details without third-party dependencies."""
    missing = "取得不可"
    env = {
        "取得時刻": now_iso(), "OS": platform.platform(),
        "アーキテクチャ": platform.machine(), "Python": sys.version.replace("\n", " "),
        "Python実行ファイル": sys.executable, "CPU": platform.processor() or missing,
        "CPU論理コア数": os.cpu_count(), "物理メモリ合計": missing,
        "利用可能メモリ（取得時点）": missing,
    }
    if platform.system() == "Linux":
        try:
            cpu = Path("/proc/cpuinfo").read_text(errors="replace")
            names = re.findall(r"^model name\s*:\s*(.*)$", cpu, re.M)
            if names:
                env["CPU"] = "; ".join(dict.fromkeys(names))
            cores = set()
            for block in cpu.split("\n\n"):
                fields = dict(line.split(":", 1) for line in block.splitlines() if ":" in line)
                fields = {k.strip(): v.strip() for k, v in fields.items()}
                if "physical id" in fields and "core id" in fields:
                    cores.add((fields["physical id"], fields["core id"]))
            if cores:
                env["CPU物理コア数"] = len(cores)
            mem = Path("/proc/meminfo").read_text()
            for key, label in (("MemTotal", "物理メモリ合計"), ("MemAvailable", "利用可能メモリ（取得時点）")):
                match = re.search(r"^" + key + r":\s*(\d+)\s+kB", mem, re.M)
                if match:
                    env[label] = f"{int(match[1]) / 1024**2:.2f} GiB"
        except OSError:
            pass
    elif platform.system() == "Windows":
        ps = ("[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; "
              "$c=@(Get-CimInstance Win32_Processor); $o=Get-CimInstance Win32_OperatingSystem; "
              "[pscustomobject]@{cpu=($c.Name -join '; '); cores=($c|Measure-Object NumberOfCores -Sum).Sum; "
              "total=[double]$o.TotalVisibleMemorySize*1024; available=[double]$o.FreePhysicalMemory*1024}|ConvertTo-Json -Compress")
        try:
            raw = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", ps],
                                 capture_output=True, timeout=10, text=True, encoding="utf-8", errors="replace").stdout
            data = json.loads(raw.lstrip("\ufeff"))
            env["CPU"] = data.get("cpu", env["CPU"])
            env["CPU物理コア数"] = data.get("cores", missing)
            for key, label in (("total", "物理メモリ合計"), ("available", "利用可能メモリ（取得時点）")):
                env[label] = f"{float(data[key]) / 1024**3:.2f} GiB"
        except (OSError, subprocess.TimeoutExpired, ValueError, KeyError, TypeError):
            pass
    if hasattr(os, "sched_getaffinity"):
        try:
            env["CPU affinityで利用可能な論理コア数"] = len(os.sched_getaffinity(0))
        except OSError:
            pass
    env["GPU情報の範囲"] = "NVIDIAはnvidia-smiから取得。他社GPUは対象外。"
    smi = shutil.which("nvidia-smi")
    if not smi and os.name == "nt":
        candidate = Path(os.environ.get("ProgramW6432", r"C:\Program Files")) / "NVIDIA Corporation" / "NVSMI" / "nvidia-smi.exe"
        if candidate.is_file():
            smi = str(candidate)
    env["NVIDIA GPU"] = missing
    env["NVIDIAドライバー"] = missing
    env["CUDA（ドライバー対応上限・nvidia-smi）"] = missing
    if smi:
        try:
            raw = subprocess.run([smi, "-q", "-x"], capture_output=True, timeout=10,
                                 text=True, encoding="utf-8", errors="replace").stdout
            import xml.etree.ElementTree as ET
            root = ET.fromstring(raw) if raw else None
            if root is not None:
                env["NVIDIAドライバー"] = root.findtext("driver_version") or missing
                env["CUDA（ドライバー対応上限・nvidia-smi）"] = root.findtext("cuda_version") or missing
                env["NVIDIA GPU"] = [{"GPU": g.findtext("product_name") or missing,
                                     "PCI bus ID": g.findtext("pci/pci_bus_id") or missing,
                                     "VRAM合計": g.findtext("fb_memory_usage/total") or missing,
                                     "VRAM使用量（取得時点）": g.findtext("fb_memory_usage/used") or missing,
                                     "VRAM空き（取得時点）": g.findtext("fb_memory_usage/free") or missing}
                                    for g in root.findall("gpu")] or missing
        except (OSError, subprocess.TimeoutExpired, Exception):
            pass
        if env["CUDA（ドライバー対応上限・nvidia-smi）"] == missing:
            try:
                raw = subprocess.run([smi], capture_output=True, timeout=10, text=True,
                                     encoding="utf-8", errors="replace").stdout
                match = re.search(r"CUDA Version:\s*([\d.]+)", raw)
                if match:
                    env["CUDA（ドライバー対応上限・nvidia-smi）"] = match[1]
            except (OSError, subprocess.TimeoutExpired):
                pass
    nvcc = shutil.which("nvcc")
    if not nvcc and os.environ.get("CUDA_PATH"):
        candidate = Path(os.environ["CUDA_PATH"]) / "bin" / ("nvcc.exe" if os.name == "nt" else "nvcc")
        if candidate.is_file():
            nvcc = str(candidate)
    try:
        env["CUDA Toolkit（nvcc）"] = subprocess.run([nvcc, "--version"], capture_output=True, timeout=10,
                                                   text=True, encoding="utf-8", errors="replace").stdout.strip() if nvcc else "未検出"
    except (OSError, subprocess.TimeoutExpired):
        env["CUDA Toolkit（nvcc）"] = "未検出"
    for name in ("numpy", "scipy", "matplotlib", "numba", "cupy", "cupy-cuda11x", "cupy-cuda12x", "cupy-cuda13x"):
        try:
            env["Pythonパッケージ " + name] = importlib.metadata.version(name)
        except importlib.metadata.PackageNotFoundError:
            pass
    for name in ("CUDA_VISIBLE_DEVICES", "OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
        if name in os.environ:
            env["環境変数 " + name] = os.environ[name]
    env["注記"] = "レポート生成側の環境を記録しています。対象コマンドが別Python・コンテナー・リモート環境の場合は一致しないことがあります。"
    return env


def pump(pipe, path: Path, display: bool, display_lock: threading.Lock, source_encoding: str):
    """Keep the original bytes and normalize CRLF to LF, including at chunk edges."""
    pending_cr = False
    with path.open("wb") as log:
        while True:
            block = pipe.read(65536)
            data = (b"\r" if pending_cr else b"") + block
            pending_cr = False
            if data.endswith(b"\r"):
                data = data[:-1]
                pending_cr = True
            normalized = data.replace(b"\r\n", b"\n")
            if not block and pending_cr:
                normalized += b"\r"
                pending_cr = False
            log.write(normalized)
            if display and normalized:
                with display_lock:
                    try:
                        sys.stdout.buffer.write(normalized)
                        sys.stdout.buffer.flush()
                    except (AttributeError, OSError):
                        sys.stdout.write(normalized.decode(source_encoding, errors="replace"))
                        sys.stdout.flush()
            if not block:
                break


def terminate_process(proc: subprocess.Popen, shell: bool):
    if proc.poll() is not None:
        return
    try:
        if os.name != "nt":
            os.killpg(proc.pid, signal.SIGTERM)
        else:
            try:
                subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"],
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                               timeout=5, check=False)
            except (OSError, subprocess.TimeoutExpired):
                proc.terminate()
        proc.wait(timeout=3)
    except (OSError, subprocess.TimeoutExpired):
        try:
            if os.name != "nt":
                os.killpg(proc.pid, signal.SIGKILL)
            else:
                proc.kill()
        except OSError:
            pass


def execute(command: list[str], cwd: Path, shell: bool, timeout: float, display: bool,
            stdout_path: Path, stderr_path: Path, source_encoding: str):
    started = now_iso()
    t0 = time.perf_counter()
    failure = ""
    timed_out = False
    returncode = None
    popen_command = command
    if shell:
        popen_command = subprocess.list2cmdline(command) if os.name == "nt" else shlex.join(command)
    try:
        kwargs = {"start_new_session": os.name != "nt"}
        if os.name == "nt":
            kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
        proc = subprocess.Popen(popen_command, cwd=cwd, shell=shell, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, **kwargs)
        lock = threading.Lock()
        out_thread = threading.Thread(target=pump, args=(proc.stdout, stdout_path, display, lock, source_encoding), daemon=True)
        err_thread = threading.Thread(target=pump, args=(proc.stderr, stderr_path, display, lock, source_encoding), daemon=True)
        out_thread.start(); err_thread.start()
        try:
            proc.wait(timeout=None if timeout <= 0 else timeout)
            returncode = proc.returncode
        except subprocess.TimeoutExpired:
            timed_out = True
            failure = f"タイムアウト（{timeout:g} 秒）に達したため、プロセスを終了しました。"
            terminate_process(proc, shell)
            returncode = 124
        except KeyboardInterrupt:
            failure = "ユーザー操作で中断されました。"
            terminate_process(proc, shell)
            returncode = 130
        out_thread.join(); err_thread.join()
    except OSError as exc:
        failure = f"コマンドを起動できませんでした: {exc}"
        returncode = 127
        stdout_path.touch(exist_ok=True); stderr_path.touch(exist_ok=True)
    return {"started": started, "finished": now_iso(), "elapsed": time.perf_counter() - t0,
            "returncode": returncode, "timed_out": timed_out, "failure": failure}


def scan_text(relpath: str, text: str, error_re, warning_re, ignore_re, max_hits: int):
    hits = []
    for number, line in enumerate(text.splitlines(), 1):
        if ignore_re and ignore_re.search(line):
            continue
        kind = "ERROR" if error_re.search(line) else "WARNING" if warning_re.search(line) else None
        if kind:
            hits.append({"file": relpath, "line": number, "kind": kind, "text": line.rstrip()})
            if len(hits) >= max_hits:
                break
    return hits


def scan_logs(root: Path, changed: list[str], out: Path, args):
    error_re = re.compile(args.error_regex, re.IGNORECASE)
    warning_re = re.compile(args.warning_regex, re.IGNORECASE)
    ignore_re = re.compile(args.ignore_log_regex, re.IGNORECASE) if args.ignore_log_regex else None
    exts = {x.lower() if x.startswith(".") else "." + x.lower() for x in parse_csv(args.log_exts)}
    hits = []
    candidates = [(root / n, n) for n in changed if (root / n).suffix.lower() in exts]
    candidates.extend([(out / "stdout.log", "stdout.log"), (out / "stderr.log", "stderr.log")])
    for path, label in candidates:
        try:
            with path.open("rb") as stream:
                data = stream.read(args.max_read_bytes + 1)
            truncated = len(data) > args.max_read_bytes
            text = data[:args.max_read_bytes].decode(args.encoding, errors="replace")
            file_hits = scan_text(label, text, error_re, warning_re, ignore_re, args.max_hits_per_file)
            if truncated and file_hits:
                file_hits[-1]["text"] += " [読み込み上限に達しました]"
            hits.extend(file_hits)
        except OSError:
            continue
    return hits


def copy_artifacts(root: Path, out: Path, names: list[str]):
    errors = []
    copied = {}
    for name in names:
        source = root / name
        destination = out / "artifacts" / name
        try:
            destination.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(source, destination)
            copied[name] = Path("artifacts") / name
        except OSError as exc:
            errors.append(f"{name}: {exc}")
    return copied, errors


def human_size(value: int) -> str:
    units = ("B", "KiB", "MiB", "GiB", "TiB")
    size = float(value)
    for unit in units:
        if size < 1024 or unit == units[-1]:
            return f"{int(size)} {unit}" if unit == "B" else f"{size:.2f} {unit}"
        size /= 1024
    return f"{value} B"


def make_rows(names, before, after, copied):
    rows = []
    for name in names:
        old, new = before.get(name), after.get(name)
        rows.append({"name": name, "old_size": old[0] if old else None,
                     "new_size": new[0] if new else None,
                     "artifact": copied.get(name)})
    return rows


def make_html(data: dict, out: Path, encoding: str, max_chars: int) -> str:
    e = html.escape
    def table(rows):
        if not rows:
            return "<p>なし</p>"
        body = []
        for row in rows:
            name = e(row["name"])
            if row["artifact"]:
                href = quote(row["artifact"].as_posix(), safe="/")
                name = f'<a href="{e(href, quote=True)}">{name}</a>'
            old = "—" if row["old_size"] is None else str(row["old_size"])
            new = "—" if row["new_size"] is None else str(row["new_size"])
            body.append(f"<tr><td>{name}</td><td>{old}</td><td>{new}</td></tr>")
        return "<table><tr><th>ファイル</th><th>実行前 bytes</th><th>実行後 bytes</th></tr>" + "".join(body) + "</table>"
    stdout = (out / "stdout.log").read_bytes().decode(encoding, errors="replace")
    stderr = (out / "stderr.log").read_bytes().decode(encoding, errors="replace")
    env_rows = "".join(f"<tr><th>{e(str(k))}</th><td><pre>{e(json.dumps(v, ensure_ascii=False, indent=2) if isinstance(v, (dict,list)) else str(v))}</pre></td></tr>" for k,v in data["environment"].items())
    hits = "<p>該当なし</p>" if not data["hits"] else "<table><tr><th>種類</th><th>ファイル</th><th>行</th><th>内容</th></tr>" + "".join(f"<tr><td>{e(h['kind'])}</td><td>{e(h['file'])}</td><td>{h['line']}</td><td>{e(h['text'])}</td></tr>" for h in data["hits"][:data["max_log_hits"]]) + "</table>"
    images = []
    for name in data["created"] + data["modified"]:
        artifact = data["copied"].get(name)
        if artifact and Path(name).suffix.lower() in IMAGE_EXTS:
            href = quote(artifact.as_posix(), safe="/")
            images.append(f'<details><summary>{e(name)}</summary><a href="{e(href, quote=True)}"><img loading="lazy" src="{e(href, quote=True)}" alt="{e(name, quote=True)}"></a></details>')
    def log_block(text):
        clipped = text[:max_chars]
        if len(text) > max_chars:
            clipped += "\n\n... レポート表示を省略しました。完全なログは同梱ファイルを参照してください ..."
        return f"<pre>{e(clipped)}</pre>"
    cmd = subprocess.list2cmdline(data["command"]) if os.name == "nt" else shlex.join(data["command"])
    return f'''<!doctype html><html lang="ja"><head><meta charset="utf-8"><title>コマンド実行レポート</title>
<style>body{{font-family:system-ui,sans-serif;max-width:1100px;margin:32px auto;padding:0 16px;line-height:1.6}}pre{{white-space:pre-wrap;overflow-wrap:anywhere;background:#f3f5f7;padding:16px}}details{{border:1px solid #ccd3dc;border-radius:6px;padding:12px;margin:12px 0}}summary{{cursor:pointer;font-weight:bold}}table{{border-collapse:collapse;width:100%;margin-top:12px}}th,td{{border:1px solid #ddd;padding:6px;text-align:left;overflow-wrap:anywhere}}img{{max-width:100%;height:auto}}</style></head><body>
<h1>コマンド実行レポート</h1><p>作業ディレクトリ: {e(data['cwd'])}<br>開始: {e(data['started'])}<br>終了: {e(data['finished'])}<br>実行時間: {data['elapsed']:.6f} 秒<br>終了コード: {data['returncode']}<br>タイムアウト: {data['timed_out']}<br>差分ハッシュ方式: {e(data['hash_mode'])}</p>
<pre>{e(cmd)}</pre>{('<p>'+e(data['failure'])+'</p>') if data['failure'] else ''}
<details open><summary>実行環境</summary><p><a href="environment.json">environment.json</a></p><table>{env_rows}</table></details>
<details><summary>標準出力</summary><p><a href="stdout.log">stdout.log</a></p>{log_block(stdout)}</details><details><summary>標準エラー</summary><p><a href="stderr.log">stderr.log</a></p>{log_block(stderr)}</details>
<details open><summary>新規作成 ({len(data['created'])})</summary>{table(data['rows_created'])}</details><details open><summary>更新 ({len(data['modified'])})</summary>{table(data['rows_modified'])}</details><details open><summary>削除 ({len(data['deleted'])})</summary>{table(data['rows_deleted'])}</details>
<details><summary>警告・エラー検出 ({len(data['hits'])})</summary>{hits}</details><details><summary>新規・更新画像 ({len(images)})</summary>{''.join(images) or '<p>なし</p>'}</details>
<details><summary>比較時・コピー時のエラー ({len(data['errors'])})</summary><pre>{e(chr(10).join(data['errors']))}</pre></details>
<p>比較は作業ディレクトリ以下の通常ファイルを対象とし、除外パターンと出力フォルダーを除きます。実行中に作成・削除されたファイルは検出できません。新規・更新ファイルは artifacts/ 以下にコピーされています。</p></body></html>'''


def md_escape(text: str) -> str:
    return text.replace("|", r"\|").replace("\n", " ")


def make_markdown(data: dict, out: Path, encoding: str, max_chars: int) -> str:
    lines = ["# コマンド実行レポート", "", "| 項目 | 値 |", "|---|---|",
             f"| 作業ディレクトリ | {md_escape(data['cwd'])} |", f"| 開始 | {data['started']} |",
             f"| 終了 | {data['finished']} |", f"| 実行時間 | {data['elapsed']:.6f} 秒 |",
             f"| 終了コード | {data['returncode']} |", f"| タイムアウト | {data['timed_out']} |", f"| 差分ハッシュ方式 | {data['hash_mode']} |", "", "## コマンド", "",
             "```text", subprocess.list2cmdline(data["command"]) if os.name == "nt" else shlex.join(data["command"]), "```", ""]
    if data["failure"]:
        lines += [f"実行状態: {md_escape(data['failure'])}", ""]
    for title, names, rows in (("新規作成", data["created"], data["rows_created"]), ("更新", data["modified"], data["rows_modified"]), ("削除", data["deleted"], data["rows_deleted"])):
        lines += [f"## {title} ({len(names)})", "", "| ファイル | 実行前 bytes | 実行後 bytes |", "|---|---:|---:|"]
        if not rows:
            lines += ["| なし | | |"]
        for row in rows:
            label = md_escape(row["name"])
            if row["artifact"]:
                label = f"[{label}](<{row['artifact'].as_posix()}>)"
            lines.append(f"| {label} | {row['old_size'] if row['old_size'] is not None else '—'} | {row['new_size'] if row['new_size'] is not None else '—'} |")
        lines.append("")
    lines += ["## 警告・エラー検出", ""]
    if not data["hits"]:
        lines += ["該当なし。", ""]
    else:
        lines += ["| 種類 | ファイル | 行 | 内容 |", "|---|---|---:|---|"]
        for hit in data["hits"][:data["max_log_hits"]]:
            lines.append(f"| {hit['kind']} | {md_escape(hit['file'])} | {hit['line']} | {md_escape(hit['text'])} |")
        lines.append("")
    for label, filename in (("標準出力", "stdout.log"), ("標準エラー", "stderr.log")):
        text = (out / filename).read_bytes().decode(encoding, errors="replace")
        clipped = text[:max_chars]
        if len(text) > max_chars:
            clipped += "\n\n... レポート表示を省略しました。完全なログは同梱ファイルを参照してください ..."
        fence = "````" if "```" in clipped else "```"
        lines += [f"## {label}", "", f"ログファイル: [{filename}](<{filename}>)", "", fence + "text", clipped.rstrip() or "(出力なし)", fence, ""]
    lines += ["## 実行環境", "", "詳細は [environment.json](<environment.json>) を参照してください。", "", "```json", json.dumps(data["environment"], ensure_ascii=False, indent=2), "```", ""]
    images = [n for n in data["created"] + data["modified"] if n in data["copied"] and Path(n).suffix.lower() in IMAGE_EXTS]
    lines += ["## 新規・更新画像", ""]
    lines.extend(f"![{md_escape(n)}](<{data['copied'][n].as_posix()}>)" for n in images)
    if not images:
        lines.append("該当なし。")
    lines.append("")
    if data["errors"]:
        lines += ["## 比較・コピー時のエラー", "", "```text", *data["errors"], "```", ""]
    return "\n".join(lines)


def build_parser():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter,
        epilog="例: python run_report.py --cwd ./case --timeout 3600 --ignore .git,.venv,__pycache__ --cmd python simulate.py --temperature 300")
    p.add_argument("--cwd", type=Path, default=Path.cwd(), help="実行・比較する作業ディレクトリ")
    p.add_argument("--output-dir", type=Path, help="専用レポートフォルダー。既定はcwd/run_report_日時")
    p.add_argument("--timeout", type=float, default=0, help="タイムアウト秒。0以下は無制限")
    p.add_argument("--shell", action="store_true", help="シェル経由で実行（パイプやリダイレクト向け）")
    p.add_argument("--display-output", choices=("combined", "none"), default="combined", help="実行中の画面表示")
    p.add_argument("--format", choices=("html", "md", "both"), default="html", help="生成するレポート形式")
    p.add_argument("--ignore", default=DEFAULT_IGNORE, help="比較から除外するfnmatchパターン（カンマ区切り）")
    p.add_argument("--hash", choices=("none", "changed", "all"), default="all", dest="hash_mode",
                   help="none=サイズ/日時で判定、changed=候補のみハッシュ、all=全ファイルSHA256で判定")
    p.add_argument("--log-exts", default=DEFAULT_LOG_EXTS, help="走査するログ拡張子")
    p.add_argument("--error-regex", default=DEFAULT_ERROR_RE, help="ERRORとして検出する正規表現")
    p.add_argument("--warning-regex", default=DEFAULT_WARNING_RE, help="WARNINGとして検出する正規表現")
    p.add_argument("--ignore-log-regex", default="", help="ログ走査時に除外する正規表現")
    p.add_argument("--encoding", default=locale.getpreferredencoding(False), help="対象コマンドおよびログの文字コード")
    p.add_argument("--max-read-bytes", type=int, default=2_000_000, help="走査時に各ログから読む最大バイト数")
    p.add_argument("--max-output-chars", type=int, default=30_000, help="レポート内のstdout/stderr表示上限")
    p.add_argument("--max-log-hits", type=int, default=300, help="レポートに表示する警告・エラー数")
    p.add_argument("--max-hits-per-file", type=int, default=100, help="各ファイルから記録する警告・エラー数")
    p.add_argument("--cmd", nargs=argparse.REMAINDER, required=True, help="実行コマンドと引数。最後に指定")
    return p


def main() -> int:
    args = build_parser().parse_args()
    command = args.cmd
    if command and command[0] == "--":
        command = command[1:]
    if not command:
        print("ERROR: --cmd の後にコマンドを指定してください", file=sys.stderr)
        return 2
    try:
        "".encode(args.encoding)
    except LookupError:
        print(f"ERROR: 不明な文字コードです: {args.encoding}", file=sys.stderr)
        return 2
    if args.max_read_bytes < 0 or args.max_output_chars < 0 or args.max_log_hits < 0 or args.max_hits_per_file < 1:
        print("ERROR: 上限値が不正です", file=sys.stderr)
        return 2
    try:
        re.compile(args.error_regex); re.compile(args.warning_regex)
        if args.ignore_log_regex:
            re.compile(args.ignore_log_regex)
    except re.error as exc:
        print(f"ERROR: 正規表現が不正です: {exc}", file=sys.stderr)
        return 2
    cwd = args.cwd.resolve()
    if not cwd.is_dir():
        print(f"ERROR: 作業ディレクトリがありません: {cwd}", file=sys.stderr)
        return 2
    out = (args.output_dir if args.output_dir else Path("run_report_" + datetime.now().strftime("%Y%m%d_%H%M%S_%f")))
    out = (cwd / out).resolve() if not out.is_absolute() else out.resolve()
    try:
        out.mkdir(parents=True, exist_ok=False)
    except OSError as exc:
        print(f"ERROR: 新しい出力フォルダーを作成できません: {exc}", file=sys.stderr)
        return 2
    excluded = out if out.is_relative_to(cwd) else None
    patterns = parse_csv(args.ignore)
    environment = command_environment()
    (out / "environment.json").write_text(json.dumps(environment, ensure_ascii=False, indent=2), encoding="utf-8")
    # "changed" keeps before-run hashes, then hashes only files whose size or
    # mtime changed after the command. "all" hashes every file on both passes.
    before, errors_before = snapshot(cwd, excluded, patterns,
                                     "all" if args.hash_mode in ("all", "changed") else "none")
    stdout_path, stderr_path = out / "stdout.log", out / "stderr.log"
    display = args.display_output == "combined"
    print(f"[run_report] cwd: {cwd}\n[run_report] command: {command}", flush=True)
    result = execute(command, cwd, args.shell, args.timeout, display, stdout_path, stderr_path, args.encoding)
    after, errors_after = snapshot(cwd, excluded, patterns, "all" if args.hash_mode == "all" else "none")
    if args.hash_mode == "changed":
        candidates = {name for name in before.keys() & after.keys() if before[name][:2] != after[name][:2]}
        for name in candidates:
            try:
                size, mtime, _ = after[name]
                after[name] = (size, mtime, sha256(cwd / name))
            except OSError:
                pass
    created, modified, deleted = compare(before, after, cwd, args.hash_mode)
    changed = created + modified
    copied, copy_errors = copy_artifacts(cwd, out, changed)
    hits = scan_logs(cwd, changed, out, args)
    data = {**result, "cwd": str(cwd), "command": command, "environment": environment, "hash_mode": args.hash_mode,
            "created": created, "modified": modified, "deleted": deleted, "copied": copied,
            "hits": hits, "max_log_hits": args.max_log_hits,
            "rows_created": make_rows(created, before, after, copied),
            "rows_modified": make_rows(modified, before, after, copied),
            "rows_deleted": make_rows(deleted, before, after, copied),
            "errors": ["実行前: " + x for x in errors_before] + ["実行後: " + x for x in errors_after] + copy_errors}
    if args.format in ("html", "both"):
        (out / "report.html").write_text(make_html(data, out, args.encoding, args.max_output_chars), encoding="utf-8")
    if args.format in ("md", "both"):
        (out / "report.md").write_text(make_markdown(data, out, args.encoding, args.max_output_chars), encoding="utf-8", newline="\n")
    print(f"\n[run_report] New={len(created)}, Modified={len(modified)}, Deleted={len(deleted)}")
    print(f"[run_report] Report folder: {out}")
    if args.format in ("html", "both"):
        print(f"[run_report] HTML: {out / 'report.html'}")
    if args.format in ("md", "both"):
        print(f"[run_report] Markdown: {out / 'report.md'}")
    return int(result["returncode"] if result["returncode"] is not None else 1)


if __name__ == "__main__":
    sys.exit(main())
