#!/usr/bin/env python3
"""Gemini Notebook（旧NotebookLM）へ入れる前のローカル事前検査。

サービスには接続しない。ローカルで観測できる条件だけを見る。
"""

from __future__ import annotations

import argparse
import json
import time
from pathlib import Path

SUPPORTED = {
    ".3g2", ".3gp", ".aac", ".aif", ".aifc", ".aiff", ".amr", ".au",
    ".avi", ".avif", ".bmp", ".cda", ".csv", ".docx", ".epub", ".gif",
    ".heic", ".heif", ".ico", ".jp2", ".jpe", ".jpeg", ".jpg", ".m4a",
    ".md", ".mid", ".mp3", ".mp4", ".mpeg", ".ogg", ".opus", ".pdf",
    ".png", ".pptx", ".ra", ".ram", ".snd", ".tif", ".tiff", ".txt",
    ".wav", ".webp", ".wma",
}


def inspect_file(path: Path, max_bytes: int) -> dict:
    issues: list[str] = []
    size = path.stat().st_size
    suffix = path.suffix.lower()
    if suffix not in SUPPORTED:
        issues.append("unsupported_extension")
    if size == 0:
        issues.append("empty_file")
    if size > max_bytes:
        issues.append("over_size_limit")

    head = path.read_bytes()[:8192]
    if suffix == ".pdf" and size:
        if not head.startswith(b"%PDF-"):
            issues.append("pdf_signature_mismatch")
        elif b"/Encrypt" in head:
            issues.append("pdf_encryption_marker")
    if suffix in {".docx", ".pptx", ".epub"} and size and not head.startswith(b"PK"):
        issues.append("zip_container_signature_mismatch")

    return {
        "file": path.name,
        "bytes": size,
        "status": "passed" if not issues else "failed",
        "issues": issues,
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("directory", type=Path)
    parser.add_argument("--max-bytes", type=int, default=200 * 1024 * 1024)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

    started = time.perf_counter()
    results = [
        inspect_file(p, args.max_bytes)
        for p in sorted(args.directory.iterdir())
        if p.is_file()
    ]
    report = {
        "method": "local_static_preflight",
        "service_connection": False,
        "max_bytes": args.max_bytes,
        "files_checked": len(results),
        "passed": sum(r["status"] == "passed" for r in results),
        "failed": sum(r["status"] == "failed" for r in results),
        "runtime_ms": round((time.perf_counter() - started) * 1000, 3),
        "results": results,
    }
    rendered = json.dumps(report, ensure_ascii=False, indent=2)
    if args.output:
        args.output.write_text(rendered + "\n", encoding="utf-8")
    print(rendered)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
