import nexustrade as nt


def create_bear_put_spread():
    asset = nt.stock_asset("SPY")
    return nt.portfolio(
        "Public SEO example - Bear put spread",
        [
            nt.strategy(
                "Open Bear put spread",
                ((nt.Price(asset) < nt.SMA(asset, 50, "Day")) & (nt.OptionPositionCount("SPY", "put", "long", "vertical") == nt.Value(0))),
                nt.open_option(
                    builder=nt.options_builder(
                        legs=[
                            nt.leg(
                                option_type="put",
                                direction="long",
                                min_days_to_expiration=30,
                                max_days_to_expiration=45,
                                preference="nearest",
                                distance=0,
                                ratio=1
                            ),
                            nt.leg(
                                option_type="put",
                                direction="short",
                                min_days_to_expiration=30,
                                max_days_to_expiration=45,
                                preference="nearest",
                                distance=5,
                                ratio=1
                            )
                        ],
                        underlying_symbol="SPY",
                        spread_type="vertical"
                    ),
                    allocation={'type': 'contracts', 'amount': 1}
                )
            ),
            nt.strategy(
                "Close when signal invalidates",
                (nt.Price(asset) >= nt.SMA(asset, 50, "Day")),
                nt.close_option(
                    underlyings=['SPY'],
                    spread_type="vertical",
                    close_scope="spread",
                    quantity={'type': 'all'}
                )
            ),
            nt.strategy(
                "Close at 14 DTE",
                (nt.Value(1) > nt.Value(0)),
                nt.close_option(
                    underlyings=['SPY'],
                    spread_type="vertical",
                    close_scope="spread",
                    quantity={'type': 'all'},
                    triggers=[nt.dte_trigger(max_dte=14)]
                )
            ),
        ],
        initial_value=10000,
        supports_fractional_shares=False,
        alerts_enabled=False,
        dividend_policy='cash',
    )


def backtest_bear_put_spread(client=None):
    client = client or nt.NexusTradeClient.from_environment()
    operation = client.create_backtest(
        nt.backtest(
            create_bear_put_spread(),
            start_date="2024-01-01", end_date="2024-12-31",
            interval="Day", baseline_symbol="SPY",
            initial_value=10000, generate_events=True,
            dividend_policy="cash",
            fee_config={"Stock": {"type": "percent", "amount": 0.1},
                        "Cryptocurrency": {"type": "percent", "amount": 0.7},
                        "Option": {"type": "dollars", "amount": 0.65}},
        ),
        idempotency_key="explore-bear-put-spread-2024-spy-v1",
    )
    return client.wait_for_backtest(operation["id"])


# Build locally: book = create_bear_put_spread()
# Run and inspect: completed = backtest_bear_put_spread(); print(completed["result"])
