"""Synthetic record/replay example v1, created 2026-10-07; Python 3.9+.

No external dependencies, network calls, market data, or trading functionality.
This is a new public example, not the original September experiment runner.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import math
from pathlib import Path
import platform
import sys
import uuid


BASE = Path(__file__).resolve().parent
VERSION = "quant-records-v1"
STABLE_FILES = ("inputs.json", "config.json", "result.json", "report.md")
FIXED_FIELDS = ("example_version", "python_version", "input_hash", "config_hash",
                "code_hash", "status", "error_type", "reason")
RUN_NAMES = ("baseline_success", "baseline_failure", "replay_success", "replay_failure")


class VerificationError(Exception):
    pass


def json_bytes(value):
    return (json.dumps(value, sort_keys=True, ensure_ascii=False,
                       indent=2, allow_nan=False) + "\n").encode("utf-8")


def reject_constant(value):
    raise ValueError("non-finite JSON number: " + value)


def read_json(path):
    return json.loads(Path(path).read_text(encoding="utf-8"), parse_constant=reject_constant)


def digest(data):
    return hashlib.sha256(data).hexdigest()


def utc_now():
    return datetime.now(timezone.utc).isoformat()


def finite_number(value):
    return (isinstance(value, (int, float)) and not isinstance(value, bool)
            and (isinstance(value, int) or math.isfinite(value)))


def weights(probabilities, threshold):
    if not isinstance(probabilities, dict) or not probabilities or any(
        not isinstance(key, str) or not key or not finite_number(value) or not 0 <= value <= 1
        for key, value in probabilities.items()
    ):
        raise ValueError("probabilities must be nonempty and within [0, 1]")
    if not finite_number(threshold) or not 0 <= threshold <= 1:
        raise ValueError("threshold must be a finite number within [0, 1]")
    selected = [key for key, value in probabilities.items() if value >= threshold]
    return {
        "weights": {key: 1.0 / len(selected) if key in selected else 0.0
                    for key in sorted(probabilities)},
        "cash_weight": 0.0 if selected else 1.0,
    }


def report_from_files(run_dir):
    record = read_json(run_dir / "record.json")
    lines = ["# Synthetic probability check", "", "Status: " + record["status"], ""]
    if record["status"] == "SUCCEEDED":
        result = read_json(run_dir / "result.json")
        lines += ["| Asset | Weight |", "| --- | --- |"]
        lines += [f"| {key} | {value} |" for key, value in sorted(result["weights"].items())]
        lines += ["", "Cash weight: " + str(result["cash_weight"])]
    elif record["status"] == "FAILED":
        lines += ["Error: " + record["error_type"], "", "Reason: " + record["reason"]]
    else:
        raise ValueError("cannot report an unfinished run")
    # Deliberately excludes run ID and timestamps so replay reports can match.
    return ("\n".join(lines) + "\n").encode("utf-8")


def run_case(inputs, config, runs_root):
    inputs_bytes, config_bytes = json_bytes(inputs), json_bytes(config)
    run_id = str(uuid.uuid4())
    run_dir = Path(runs_root) / run_id
    run_dir.mkdir(exist_ok=False)
    (run_dir / "inputs.json").write_bytes(inputs_bytes)
    (run_dir / "config.json").write_bytes(config_bytes)
    record = {
        "example_version": VERSION, "run_id": run_id,
        "started_at": utc_now(), "finished_at": None,
        "python_version": platform.python_version(),
        "input_hash": digest(inputs_bytes), "config_hash": digest(config_bytes),
        "code_hash": digest(Path(__file__).read_bytes()),
        "status": "RUNNING", "error_type": None, "reason": None,
    }
    (run_dir / "record.json").write_bytes(json_bytes(record))
    try:
        if not isinstance(config, dict) or set(config) != {"threshold"}:
            raise ValueError("config must contain only threshold")
        result = weights(inputs, config["threshold"])
    except ValueError as error:
        record.update(status="FAILED", error_type="ValueError", reason=str(error))
    else:
        (run_dir / "result.json").write_bytes(json_bytes(result))
        record["status"] = "SUCCEEDED"
    record["finished_at"] = utc_now()
    (run_dir / "record.json").write_bytes(json_bytes(record))
    (run_dir / "report.md").write_bytes(report_from_files(run_dir))
    return run_dir


def snapshot(directory):
    directory = Path(directory)
    return {str(path.relative_to(directory)): digest(path.read_bytes())
            for path in sorted(directory.rglob("*")) if path.is_file()}


def optional_bytes(path):
    try:
        return path.read_bytes()
    except FileNotFoundError:
        return None


def checks(out, manifest):
    try:
        # The manifest references only immediate UUID folders within the output directory.
        run_ids = [manifest["runs"][name] for name in RUN_NAMES]
        if any(str(uuid.UUID(run_id)) != run_id for run_id in run_ids):
            raise VerificationError("invalid run folder name")
        paths = {name: Path(out) / manifest["runs"][name] for name in RUN_NAMES}
        records = {name: read_json(path / "record.json") for name, path in paths.items()}
        success = ("baseline_success", "replay_success")
        failure = ("baseline_failure", "replay_failure")
        expected_result = read_json(BASE / "expected/success-result.json")
        expected_failure = read_json(BASE / "expected/failure.json")
        results = {
            "success_expected_result": all(read_json(paths[name] / "result.json") == expected_result
                                           for name in success),
            "failure_expected_record": all({key: records[name][key] for key in expected_failure} == expected_failure
                                           for name in failure),
            "failure_result_absent": all(not (paths[name] / "result.json").exists() for name in failure),
            "distinct_run_directories": len(set(run_ids)) == 4,
            "matching_stable_file_bytes": all(
                optional_bytes(paths["baseline_" + case] / filename) == optional_bytes(paths["replay_" + case] / filename)
                for case in ("success", "failure") for filename in STABLE_FILES),
            "matching_fixed_metadata": all(
                records["baseline_" + case][key] == records["replay_" + case][key]
                for case in ("success", "failure") for key in FIXED_FIELDS)
                and all(record["input_hash"] == digest((paths[name] / "inputs.json").read_bytes())
                        and record["config_hash"] == digest((paths[name] / "config.json").read_bytes())
                        and record["code_hash"] == digest(Path(__file__).read_bytes())
                        for name, record in records.items()),
            "new_run_ids": all(records[name]["run_id"] == paths[name].name for name in RUN_NAMES)
                and all(records["baseline_" + case]["run_id"] != records["replay_" + case]["run_id"]
                        for case in ("success", "failure")),
            "baseline_files_unchanged": all(snapshot(paths[name]) == manifest["baseline_sha256"][name]
                                            for name in ("baseline_success", "baseline_failure")),
            "report_matches_expected": all(
                (paths[name] / "report.md").read_bytes() == (BASE / ("expected/" + name.split("_")[1] + "-report.md")).read_bytes()
                for name in RUN_NAMES),
        }
    except (OSError, ValueError, KeyError, TypeError) as error:
        raise VerificationError("missing or invalid evidence: " + str(error)) from error
    failed = [name for name, passed in results.items() if not passed]
    if failed:
        raise VerificationError(", ".join(failed))
    return results


def run_demo(out):
    out = Path(out)
    # Each demo is a new experiment set. Never silently reuse an existing directory.
    out.mkdir(parents=True, exist_ok=False)
    config = read_json(BASE / "inputs/config.json")
    baseline = {case: run_case(read_json(BASE / ("inputs/" + case + ".json")), config, out)
                for case in ("success", "failure")}
    before = {"baseline_" + case: snapshot(path) for case, path in baseline.items()}
    replay = {case: run_case(read_json(path / "inputs.json"), read_json(path / "config.json"), out)
              for case, path in baseline.items()}
    manifest = {
        "example_version": VERSION, "verified_at": utc_now(),
        "python_version": platform.python_version(), "platform": sys.platform,
        "runs": {**{"baseline_" + case: path.name for case, path in baseline.items()},
                 **{"replay_" + case: path.name for case, path in replay.items()}},
        "baseline_sha256": before,
    }
    manifest["checks"] = checks(out, manifest)
    (out / "verification.json").write_bytes(json_bytes(manifest))
    return manifest


def verify(out):
    # Recompute instead of trusting the saved PASS booleans.
    return checks(out, read_json(Path(out) / "verification.json"))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("operation", choices=("demo", "verify"))
    parser.add_argument("--out", type=Path, required=True, help="experiment output directory")
    args = parser.parse_args()
    try:
        result = run_demo(args.out)["checks"] if args.operation == "demo" else verify(args.out)
    except (OSError, ValueError, VerificationError) as error:
        print("checks FAIL: " + str(error), file=sys.stderr)
        return 1
    print(f"checks PASS ({len(result)} checks)")
    print("success: SYN_A=0.5, SYN_B=0.0, SYN_C=0.5, cash_weight=0.0")
    print("failure: FAILED / ValueError / no result.json")
    print("evidence: " + str(args.out / "verification.json"))
    return 0


if __name__ == "__main__":
    sys.exit(main())
