#!/usr/bin/env python3
"""Run read-view smoke tests for the first available objects of selected kinds."""

from __future__ import annotations

import argparse
import base64
import json
import os
import subprocess
import sys
from pathlib import Path


def load_json(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8-sig"))


def main() -> int:
    parser = argparse.ArgumentParser(description="Smoke-test read_1c_object_view by object kind.")
    parser.add_argument("--summary", type=Path, required=True)
    parser.add_argument("--validation", type=Path, required=True)
    parser.add_argument("--route-index", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--kind", action="append", required=True)
    parser.add_argument("--top", type=int, default=5)
    args = parser.parse_args()

    summary = load_json(args.summary)
    runs = []
    for kind in args.kind:
        candidates = [
            row
            for row in summary.get("outputs") or []
            if row.get("kind") == kind
            and (row.get("storage_route_summary") or {}).get("metadata_items_with_routes", 0) > 0
        ]
        if not candidates:
            runs.append({"kind": kind, "status": "no_candidate"})
            continue
        row = candidates[0]
        name = row["name"]
        encoded = base64.b64encode(name.encode("utf-8")).decode("ascii")
        command = [
            sys.executable,
            "scripts/read_1c_object_view.py",
            "--kind",
            kind,
            "--name-b64",
            encoded,
            "--top",
            str(args.top),
            "--summary",
            str(args.summary),
            "--validation",
            str(args.validation),
            "--route-index",
            str(args.route_index),
            "--output-dir",
            str(args.output_dir),
        ]
        completed = subprocess.run(command, text=True, capture_output=True, env=os.environ.copy())
        runs.append(
            {
                "kind": kind,
                "name": name,
                "status": "ok" if completed.returncode == 0 else "failed",
                "returncode": completed.returncode,
                "stdout_tail": completed.stdout[-4000:],
                "stderr_tail": completed.stderr[-4000:],
            }
        )
    print(json.dumps({"schema": "onec_read_view_kind_smoke.v1", "runs": runs}, ensure_ascii=True, indent=2))
    return 0 if all(row["status"] in {"ok", "no_candidate"} for row in runs) else 1


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