# Copyright (c) 2026 fxtradingguide.com
# SPDX-License-Identifier: MIT

"""Print the study report. The report has no return, by design."""

from __future__ import annotations

import hashlib

from fxstudy.data import SERIES_KEY, SERIES_TITLE, Observation

SPREAD_FRACTION = 0.0001
NOTIONAL_FRACTION = 0.10
STARTING_CASH = 100_000.0
MARGIN = 1.0


def signal_digest(desired: list[int | None]) -> str:
    """Stable hash of the position after each observation.

    ``None`` is warmup (shown as ``.``). Otherwise the value is -1, 0, or 1.
    """
    parts: list[str] = []
    for value in desired:
        if value is None:
            parts.append(".")
        elif value in (-1, 0, 1):
            parts.append(str(value))
        else:
            raise SystemExit(f"signal out of range: {value}")
    payload = ",".join(parts).encode("ascii")
    return hashlib.sha256(payload).hexdigest()


def count_changes(desired: list[int | None]) -> tuple[int, int]:
    """Return (signals, filled_orders).

    A signal is a change in the desired position. Warmup (``None``) is ignored
    and the position before the first decision is flat. A signal on the last
    observation cannot fill, because the fill is the next observation.
    """
    previous = 0
    signals = 0
    filled = 0
    for index, value in enumerate(desired):
        if value is None or value == previous:
            continue
        signals += 1
        if index + 1 < len(desired):
            filled += 1
        previous = value
    return signals, filled


def fill_price(rate: float, side: int, spread: float = SPREAD_FRACTION) -> float:
    """Move a reference rate against the trader by ``spread``.

    ``side`` is +1 for a buy and -1 for a sell. ``spread`` is a fraction of the
    rate, matching backtesting.py's ``spread`` argument, not a pip count.
    """
    if side not in (1, -1):
        raise SystemExit(f"fill side must be +1 or -1, got {side}")
    if rate <= 0 or spread < 0:
        raise SystemExit("rate and spread must be positive")
    return rate * (1.0 + side * spread)


def exercise_fills(rates: list[float], desired: list[int | None]) -> int:
    """Apply ``fill_price`` to every fill. The prices are not reported."""
    previous = 0
    filled = 0
    for index, value in enumerate(desired):
        if value is None or value == previous:
            continue
        if index + 1 < len(desired):
            # Flat means close the old position. A reversal is one order in the
            # new direction, the same simplification as an exclusive order.
            side = -previous if value == 0 else value
            fill_price(rates[index + 1], side)
            filled += 1
        previous = value
    return filled


def assert_causal(length: int, compute) -> None:
    """Fail if observation ``i`` changes when later observations are removed."""
    full = compute(length)
    if len(full) != length:
        raise SystemExit(f"signal length {len(full)} != {length}")
    step = max(1, length // 20)
    indexes = list(range(0, length, step))
    if not indexes or indexes[-1] != length - 1:
        indexes.append(length - 1)
    for end in indexes:
        prefix = compute(end + 1)
        if len(prefix) != end + 1 or prefix[-1] != full[end]:
            raise SystemExit(
                f"look-ahead at index {end}: prefix ends {prefix[-1]!r}, full series has {full[end]!r}"
            )


def write_report(
    study: str,
    language: str,
    observations: list[Observation],
    desired: list[int | None],
    library_trades: str,
) -> None:
    signals, filled = count_changes(desired)
    exercised = exercise_fills([item.rate for item in observations], desired)
    if exercised != filled:
        raise SystemExit("fill count did not match the cost-path count")
    lines = [
        f"study: {study}",
        f"language: {language}",
        "data_source: ECB statistics",
        f"series: {SERIES_KEY}",
        f"series_title: {SERIES_TITLE}",
        f"period: {observations[0].date} to {observations[-1].date}",
        f"observations: {len(observations)}",
        "price: one daily reference rate, copied into Open, High, Low and Close",
        (
            "costs: spread fraction 0.0001 of the rate, applied once against the trader; "
            "commission 0; swap not modelled; slippage not modelled"
        ),
        "fills: next observation after the signal",
        (
            "position: one position; notional 10 percent of cash; "
            f"starting cash {int(STARTING_CASH)}; margin {MARGIN:g}; no leverage in this study"
        ),
        "past_performance: Past performance does not predict future results",
        "return_reported: no",
        f"signals: {signals}",
        f"filled_orders: {filled}",
        f"library_trades: {library_trades}",
        f"signal_digest: {signal_digest(desired)}",
        "status: ok",
    ]
    print("\n".join(lines))
