import nexustrade as nt


def create_covered_call():
    asset = nt.stock_asset("SPY")
    return nt.portfolio(
        "Public SEO example - Covered call",
        [
            nt.strategy(
                "Buy 100 shares for call coverage",
                (nt.PositionValue(asset) == nt.Value(0)),
                nt.buy(asset, 100, "number of assets")
            ),
            nt.strategy(
                "Open Covered call",
                (((nt.Price(asset) > nt.SMA(asset, 50, "Day")) & (nt.OptionPositionCount("SPY", "call", "short", "custom") == nt.Value(0))) & (nt.PositionValue(asset) > nt.Value(0))),
                nt.open_option(
                    builder=nt.options_builder(
                        legs=[nt.leg(option_type="call", direction="short", min_days_to_expiration=30, max_days_to_expiration=45, preference="nearest", distance=5, ratio=1)],
                        underlying_symbol="SPY",
                        spread_type="custom"
                    ),
                    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="custom",
                    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="custom",
                    close_scope="spread",
                    quantity={'type': 'all'},
                    triggers=[nt.dte_trigger(max_dte=14)]
                )
            ),
        ],
        initial_value=100000,
        supports_fractional_shares=False,
        alerts_enabled=False,
        dividend_policy='cash',
    )


def backtest_covered_call(client=None):
    client = client or nt.NexusTradeClient.from_environment()
    operation = client.create_backtest(
        nt.backtest(
            create_covered_call(),
            start_date="2024-01-01", end_date="2024-12-31",
            interval="Day", baseline_symbol="SPY",
            initial_value=100000, 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-covered-call-2024-spy-v1",
    )
    return client.wait_for_backtest(operation["id"])


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