#!/usr/bin/env python3
import sys
import json
import argparse
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--json", default="Temp/live_replay_separation_v3.json")
    parser.add_argument("--strict", action="store_true")
    args = parser.parse_args()

    json_path = ROOT / args.json
    if not json_path.exists():
        print(f"File not found: {json_path}")
        sys.exit(1)

    data = json.loads(json_path.read_text(encoding="utf-8"))
    rows = data.get("performance_rows", [])

    allowed_origins = {"operational_live", "shadow_live", "replay", "estimated"}
    replay_in_live_stats = 0
    unlabeled_row_count = 0

    for idx, row in enumerate(rows):
        origin = row.get("origin")
        if not origin:
            unlabeled_row_count += 1
            continue
        if origin not in allowed_origins:
            unlabeled_row_count += 1
            continue
        # Check if replay is mixed with live readiness stats
        if origin in ("replay", "estimated") and row.get("is_live_readiness_basis", False):
            replay_in_live_stats += 1

    if unlabeled_row_count > 0:
        print(f"Validation failed: {unlabeled_row_count} rows with invalid or missing origin")
        sys.exit(1)

    if replay_in_live_stats > 0:
        print(f"Validation failed: {replay_in_live_stats} replay/estimated rows mixed in live statistics")
        sys.exit(1)

    print("VALIDATION OK")
    sys.exit(0)

if __name__ == "__main__":
    main()
