#!/usr/bin/env python3
"""Standalone streaming extXYZ trajectory generator, byte-offset indexer, and random-access verifier.

Demonstrates the O(1)-memory streaming indexing and random frame-seek pattern verified in Track 11
(10.00 GB / 64,206 frames indexed in 122.05 s, tail random reads in 1.14 s) using Python 3 stdlib only.

Usage:
    # Quick local sanity run (2 MB temporary file, auto-deleted):
    python3 validation/scripts/reproduce_streaming_extxyz.py --target-mb 2

    # Full 10 GB stress reproduction (requires >= 11 GB free disk space):
    python3 validation/scripts/reproduce_streaming_extxyz.py --target-gb 10
"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
import tempfile
import time
from pathlib import Path


def build_frame(frame_idx: int, n_atoms: int = 3072) -> bytes:
    side = round(n_atoms ** (1.0 / 3.0))
    cell_a = side * 3.85
    header = (
        f"{n_atoms}\n"
        f'Lattice="{cell_a:.6f} 0.0 0.0 0.0 {cell_a:.6f} 0.0 0.0 0.0 {cell_a:.6f}" '
        f'Properties=species:S:1:pos:R:3 frame={frame_idx} time_fs={frame_idx * 1.0:.1f}\n'
    )
    lines = [header]
    phase = 0.01 * math.sin(frame_idx * 0.1)
    for i in range(n_atoms):
        ix = i % side
        iy = (i // side) % side
        iz = i // (side * side)
        x = ix * 3.85 + phase
        y = iy * 3.85 - phase
        z = iz * 3.85 + 0.5 * phase
        lines.append(f"Ar {x:12.6f} {y:12.6f} {z:12.6f}\n")
    return "".join(lines).encode("ascii")


def index_extxyz_streaming(path: Path) -> list[tuple[int, int, int]]:
    """Index (byte_offset, byte_length, n_atoms) in a single O(1)-buffer streaming pass."""
    offsets: list[tuple[int, int, int]] = []
    with path.open("rb") as handle:
        while True:
            start = handle.tell()
            first = handle.readline()
            if not first:
                break
            n_atoms = int(first.strip())
            _comment = handle.readline()
            for _ in range(n_atoms):
                handle.readline()
            end = handle.tell()
            offsets.append((start, end - start, n_atoms))
    return offsets


def read_frame_at(path: Path, offset: int, length: int) -> tuple[int, str, str]:
    with path.open("rb") as handle:
        handle.seek(offset)
        raw = handle.read(length).decode("ascii")
    lines = raw.splitlines()
    return int(lines[0].strip()), lines[1], lines[-1]


def main() -> int:
    parser = argparse.ArgumentParser(description="Verify streaming extXYZ indexing & random frame reads.")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--target-mb", type=float, default=2.0, help="Target trajectory size in MB (default: 2 MB).")
    group.add_argument("--target-gb", type=float, default=None, help="Target trajectory size in GB (e.g., 10).")
    parser.add_argument("--atoms", type=int, default=512, help="Atoms per frame (default: 512 for fast run; 3072 for 10 GB run).")
    args = parser.parse_args()

    target_bytes = int((args.target_gb * 1024**3) if args.target_gb is not None else (args.target_mb * 1024**2))

    with tempfile.TemporaryDirectory(prefix="calclens-extxyz-") as tmp:
        traj = Path(tmp) / "synthetic.extxyz"
        sha = hashlib.sha256()
        written = 0
        frames = 0
        t0 = time.perf_counter()
        with traj.open("wb") as out:
            while written < target_bytes:
                payload = build_frame(frames, n_atoms=args.atoms)
                out.write(payload)
                sha.update(payload)
                written += len(payload)
                frames += 1
        gen_s = time.perf_counter() - t0

        t1 = time.perf_counter()
        index = index_extxyz_streaming(traj)
        idx_s = time.perf_counter() - t1

        assert len(index) == frames, f"Indexed {len(index)} frames, expected {frames}"

        t2 = time.perf_counter()
        tail_indices = [max(0, frames - 2), frames - 1]
        tail_checks = []
        for idx in tail_indices:
            off, length, expected_n = index[idx]
            n_atoms, comment, _last_atom = read_frame_at(traj, off, length)
            assert n_atoms == expected_n == args.atoms
            assert f"frame={idx} " in comment
            tail_checks.append({"frame": idx, "offset": off, "bytes": length})
        read_s = time.perf_counter() - t2

        print(
            json.dumps(
                {
                    "bytes_written": written,
                    "frames": frames,
                    "atoms_per_frame": args.atoms,
                    "sha256": sha.hexdigest(),
                    "generate_seconds": round(gen_s, 4),
                    "index_seconds": round(idx_s, 4),
                    "tail_random_read_seconds": round(read_s, 5),
                    "verified_tail_frames": tail_checks,
                },
                indent=2,
            )
        )
        print("STREAMING EXTXYZ INDEX & RANDOM-ACCESS VERIFICATION PASSED.")
    return 0


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