#!/usr/bin/env python3
# Copyright (c) 2026 fxtradingguide.com
# SPDX-License-Identifier: MIT

"""Donchian channel breakout study.

A close above the highest of the previous entry window goes long. A close
below the lowest of that window goes short. A long exits on a close below the
lowest of the previous, shorter, exit window, and the short is the mirror.
The current observation is not part of its own channel. The fill is the next
observation. Nothing here is a forecast or a recommendation.
"""

from __future__ import annotations

import sys
from pathlib import Path

import pandas as pd
from backtesting import Backtest

ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT / "strategies" / "shared" / "python"))

from fxstudy.data import assert_sample, load_observations
from fxstudy.library import SignalStrategy
from fxstudy.report import (
    MARGIN,
    SPREAD_FRACTION,
    STARTING_CASH,
    assert_causal,
    write_report,
)

STUDY = "donchian-breakout"
ENTRY = 20
EXIT = 10


def prior_extreme(values: list[float], window: int, highest: bool) -> list[float | None]:
    """Max or min of the previous ``window`` observations, excluding the current one."""
    if window <= 0:
        raise SystemExit("channel window must be positive")
    out: list[float | None] = [None] * len(values)
    for index in range(window, len(values)):
        sample = values[index - window : index]
        out[index] = max(sample) if highest else min(sample)
    return out


def signals(
    high: list[float],
    low: list[float],
    close: list[float],
    entry: int = ENTRY,
    exit_window: int = EXIT,
) -> list[int | None]:
    if entry <= 0 or exit_window <= 0:
        raise SystemExit("channel windows must be positive")
    entry_high = prior_extreme(high, entry, True)
    entry_low = prior_extreme(low, entry, False)
    exit_high = prior_extreme(high, exit_window, True)
    exit_low = prior_extreme(low, exit_window, False)
    position = 0
    desired: list[int | None] = []
    for index, price in enumerate(close):
        if entry_high[index] is None or exit_low[index] is None:
            desired.append(None)
            continue
        if position == 1 and price < exit_low[index]:
            position = 0
        elif position == -1 and price > exit_high[index]:
            position = 0
        if position <= 0 and price > entry_high[index]:
            position = 1
        elif position >= 0 and price < entry_low[index]:
            position = -1
        desired.append(position)
    return desired


def _assert_channel_excludes_itself() -> None:
    highest = prior_extreme([1, 3, 2, 5], 2, True)
    if highest != [None, None, 3, 3]:
        raise SystemExit(f"channel fixture failed: {highest}")


def library_trade_count(dates: list[str], rates: list[float], desired: list[int | None]) -> int:
    frame = pd.DataFrame(
        {
            "Open": rates,
            "High": rates,
            "Low": rates,
            "Close": rates,
            "Signal": [float("nan") if value is None else float(value) for value in desired],
        },
        index=pd.to_datetime(dates),
    )
    backtest = Backtest(
        frame,
        SignalStrategy,
        cash=STARTING_CASH,
        spread=SPREAD_FRACTION,
        commission=0.0,
        margin=MARGIN,
        trade_on_close=False,
        hedging=False,
        exclusive_orders=True,
    )
    return int(backtest.run()["# Trades"])


def main() -> None:
    _assert_channel_excludes_itself()
    observations = load_observations()
    assert_sample(observations)
    rates = [item.rate for item in observations]

    def compute(end: int) -> list[int | None]:
        sample = rates[:end]
        return signals(sample, sample, sample)

    assert_causal(len(rates), compute)
    desired = signals(rates, rates, rates)
    trades = library_trade_count([item.date for item in observations], rates, desired)
    write_report(STUDY, "python", observations, desired, str(trades))


if __name__ == "__main__":
    main()
