"""Run strategy command."""

from __future__ import annotations

import importlib.util
import logging
import os
import sys

import click


@click.command()
@click.argument("strategy_file")
@click.option("--mode", default=None, help="Trading mode: paper or live")
@click.option("--dashboard/--no-dashboard", default=None, help="Show TUI dashboard")
@click.option(
    "--log-level",
    default="info",
    type=click.Choice(["debug", "info", "warn", "error"], case_sensitive=False),
    help="Log level for Python and Rust",
)
def run(strategy_file: str, mode: str | None, dashboard: bool | None, log_level: str):
    """Run a strategy file.

    The strategy file should call hz.run() which blocks until interrupted.
    CLI options override the strategy's hz.run() arguments.
    """
    logging.basicConfig(
        level=getattr(logging, log_level.upper()),
        format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
        datefmt="%H:%M:%S",
    )
    os.environ.setdefault("HORIZON_LOG", log_level.lower())

    import horizon.strategy as strategy_mod

    if mode is not None:
        strategy_mod._cli_overrides["mode"] = mode
    if dashboard is not None:
        strategy_mod._cli_overrides["dashboard"] = dashboard

    spec = importlib.util.spec_from_file_location("strategy", strategy_file)
    if spec is None or spec.loader is None:
        click.echo(f"Error: cannot load {strategy_file}", err=True)
        sys.exit(1)

    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
