"""Run a bounded synthetic reproducibility check with Python's standard library.

Python 3.10+. No packages, network, randomness, market data or EdgeVeris account.
This teaching runner is NOT the EdgeVeris production execution engine. It only
supports flat/long/short target changes and no stops, partial exits or slippage.
"""
from __future__ import annotations

import argparse
import copy
import csv
import hashlib
import io
import json
import platform
import sys
from datetime import datetime, timezone
from decimal import Decimal
from pathlib import Path

sys.dont_write_bytecode = True  # Keep the downloadable fixture directory clean.
from strategy import target_positions


def encoded(value):
    """Canonical JSON used for identities and portable result artifacts."""
    return (json.dumps(value, sort_keys=True, indent=2, ensure_ascii=True) + "\n").encode("utf-8")


def fingerprint(value):
    return hashlib.sha256(value if isinstance(value, bytes) else encoded(value)).hexdigest()


def cents(value):
    amount = Decimal(value) * 100
    if not amount.is_finite() or amount != amount.to_integral_value():
        raise ValueError("This example requires exact whole cents")
    return int(amount)


def timestamp(value):
    parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if parsed.tzinfo is None or parsed.utcoffset().total_seconds() != 0:
        raise ValueError("Fixture timestamps must be explicitly UTC")
    return parsed.astimezone(timezone.utc)


def load_bars(raw, config):
    rows = list(csv.DictReader(io.StringIO(raw.decode("utf-8"))))
    if len(rows) < 2 or set(rows[0]) != {"timestamp_utc", "open", "high", "low", "close"}:
        raise ValueError("Expected at least two OHLC fixture bars")
    start = timestamp(config["data"]["start_inclusive"])
    end = timestamp(config["data"]["end_exclusive"])
    tick = Decimal(config["execution"]["tick_size"])
    previous = None
    for row in rows:
        current = timestamp(row["timestamp_utc"])
        if not start <= current < end or (previous is not None and (current - previous).total_seconds() != 60):
            raise ValueError("Fixture must be ordered consecutive minute bars within the declared period")
        previous = current
        prices = {key: Decimal(row[key]) for key in ("open", "high", "low", "close")}
        if any(not value.is_finite() or value / tick != (value / tick).to_integral_value() for value in prices.values()):
            raise ValueError("Fixture prices must be finite and tick aligned")
        if prices["low"] > min(prices.values()) or prices["high"] < max(prices.values()):
            raise ValueError("Inconsistent OHLC fixture")
    return rows


def run(config, raw_data, source_bytes, environment):
    execution = config["execution"]
    if (execution["entry"] != "next bar open" or execution["exit"] != "next bar open when target changes"
            or execution["stop_target"] != "none" or execution["force_close"] is not False
            or Decimal(execution["slippage_ticks"]) != 0):
        raise ValueError("This teaching runner only supports its declared next-open, no-stop, zero-slippage model")
    bars = load_bars(raw_data, config)
    targets = target_positions(bars, config["parameters"])
    point_value = Decimal(execution["point_value_usd"])
    fee = cents(execution["commission_per_contract_per_side_usd"])
    initial = cents(execution["initial_capital_usd"])
    if fee < 0 or point_value <= 0 or initial <= 0:
        raise ValueError("Invalid accounting inputs")
    position, entry = 0, None
    trades = []
    for index in range(1, len(bars)):
        desired = targets[index - 1]  # Current bar's close is not known yet.
        if desired == position:
            continue
        bar = bars[index]
        price = Decimal(bar["open"])
        if position:
            quantity = abs(position)
            direction = 1 if position > 0 else -1
            gross = cents((price - entry["price"]) * direction * point_value * quantity)
            commission = quantity * fee * 2
            trades.append({
                "trade": len(trades) + 1, "side": "LONG" if position > 0 else "SHORT", "quantity": quantity,
                "entry_time": entry["time"], "exit_time": bar["timestamp_utc"],
                "entry_price": str(entry["price"]), "exit_price": str(price),
                "gross_pnl_cents": gross, "commission_cents": commission,
                "slippage_cents": 0, "net_pnl_cents": gross - commission,
            })
        position = desired
        entry = {"time": bar["timestamp_utc"], "price": price} if desired else None
    if position:
        raise ValueError("Fixture ends with an open position. No silent forced close is permitted")
    equity, gross_equity, peak, max_drawdown = [initial], [initial], initial, 0
    for trade in trades:
        equity.append(equity[-1] + trade["net_pnl_cents"])
        gross_equity.append(gross_equity[-1] + trade["gross_pnl_cents"])
        peak = max(peak, equity[-1])
        max_drawdown = max(max_drawdown, peak - equity[-1])
    result = {
        "currency": "USD", "monetary_unit": "integer cents", "trades": trades,
        "targets_at_bar_close": targets, "closed_equity_cents": equity, "gross_closed_equity_cents": gross_equity,
        "summary": {
            "trades": len(trades), "round_turn_contracts": sum(row["quantity"] for row in trades),
            "gross_pnl_cents": sum(row["gross_pnl_cents"] for row in trades),
            "commission_cents": sum(row["commission_cents"] for row in trades),
            "slippage_cents": 0, "net_pnl_cents": equity[-1] - initial,
            "final_closed_equity_cents": equity[-1], "max_closed_drawdown_cents": max_drawdown,
        },
    }
    assert result["summary"]["net_pnl_cents"] == result["summary"]["gross_pnl_cents"] - result["summary"]["commission_cents"]
    identities = {
        "code": {name: fingerprint(content) for name, content in source_bytes.items()},
        "data": {"bytes_sha256": fingerprint(raw_data), "declaration_sha256": fingerprint(config["data"])},
        "parameters_sha256": fingerprint(config["parameters"]),
        "execution_sha256": fingerprint(execution),
        "environment_sha256": fingerprint(environment),
    }
    manifest = {
        "format": "edgeveris-synthetic-reproducibility-v1", "identities": identities,
        "experiment_sha256": fingerprint(identities),
        "configuration_canonical_sha256": fingerprint(config), "environment": environment,
        "result_sha256": fingerprint(result),
    }
    return result, manifest


def build_bundle(root):
    config = json.loads((root / "config.json").read_text(encoding="utf-8"))
    data = (root / "bars.csv").read_bytes()
    sources = {name: (root / name).read_bytes() for name in ("strategy.py", "run_example.py")}
    environment = {"python_implementation": platform.python_implementation(), "python_version": platform.python_version(),
                   "operating_system": platform.system(), "architecture": platform.machine(), "third_party_dependencies": []}
    baseline, manifest = run(config, data, sources, environment)
    repeated, repeated_manifest = run(config, data, sources, environment)
    assert encoded(baseline) == encoded(repeated)
    assert encoded(manifest) == encoded(repeated_manifest)
    higher_config = copy.deepcopy(config)
    higher_config["execution"]["commission_per_contract_per_side_usd"] = "6.00"
    higher, higher_manifest = run(higher_config, data, sources, environment)
    assert baseline["summary"]["net_pnl_cents"] == 26000
    assert baseline["summary"]["max_closed_drawdown_cents"] == 7000
    assert higher["summary"]["net_pnl_cents"] == 25200
    assert higher["summary"]["max_closed_drawdown_cents"] == 7200
    assert manifest["identities"]["code"] == higher_manifest["identities"]["code"]
    assert manifest["identities"]["data"] == higher_manifest["identities"]["data"]
    assert manifest["identities"]["parameters_sha256"] == higher_manifest["identities"]["parameters_sha256"]
    assert manifest["identities"]["environment_sha256"] == higher_manifest["identities"]["environment_sha256"]
    comparison = {
        "baseline_run_1_result_sha256": manifest["result_sha256"],
        "baseline_run_2_result_sha256": repeated_manifest["result_sha256"],
        "baseline_result_bytes_identical": True, "baseline_manifest_bytes_identical": True,
        "changed_input": {"path": "execution.commission_per_contract_per_side_usd", "before": "5.00", "after": "6.00"},
        "higher_fee_result_sha256": higher_manifest["result_sha256"],
        "baseline_net_pnl_cents": baseline["summary"]["net_pnl_cents"],
        "higher_fee_net_pnl_cents": higher["summary"]["net_pnl_cents"],
        "net_difference_cents": higher["summary"]["net_pnl_cents"] - baseline["summary"]["net_pnl_cents"],
        "trade_timing_prices_and_quantities_unchanged": all(
            {k: v for k, v in left.items() if k not in {"commission_cents", "net_pnl_cents"}}
            == {k: v for k, v in right.items() if k not in {"commission_cents", "net_pnl_cents"}}
            for left, right in zip(baseline["trades"], higher["trades"])
        ),
    }
    return {
        "baseline-results.json": baseline, "baseline-manifest.json": manifest,
        "higher-fee-config.json": higher_config, "higher-fee-results.json": higher,
        "higher-fee-manifest.json": higher_manifest, "comparison.json": comparison,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, help="Write six JSON artifacts here, refusing to overwrite existing files")
    args = parser.parse_args()
    bundle = build_bundle(Path(__file__).resolve().parent)
    if args.output is not None:
        args.output.mkdir(parents=True, exist_ok=True)
        if any((args.output / name).exists() for name in bundle):
            raise SystemExit("Output artifacts already exist. Choose a new output directory")
        for name, value in bundle.items():
            with (args.output / name).open("xb") as file:
                file.write(encoded(value))
    print(encoded(bundle["comparison.json"]).decode(), end="")


if __name__ == "__main__":
    if sys.version_info < (3, 10):
        raise SystemExit("Python 3.10 or later is required")
    main()
