from __future__ import annotations

import argparse
import logging
import sys
import time

from kraken_bot.config import load_config
from kraken_bot.engine import TradingBot


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Run the Kraken trading bot.")
    parser.add_argument("--config", default="config.example.json", help="Path to bot JSON config")
    parser.add_argument("--loop", action="store_true", help="Run continuously")
    parser.add_argument("--sleep", type=int, default=60, help="Seconds between loop runs")
    parser.add_argument("--log-level", default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR"])
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    logging.basicConfig(
        level=getattr(logging, args.log_level),
        format="%(asctime)s %(levelname)s %(name)s: %(message)s",
    )
    config = load_config(args.config)
    bot = TradingBot(config)

    while True:
        results = bot.run_once()
        for result in results:
            print(
                f"{result.symbol:10} {result.strategy:28} "
                f"{result.signal.side.value:4} price={result.price:.8f} {result.message}"
            )
        if not args.loop:
            return 0
        time.sleep(args.sleep)


if __name__ == "__main__":
    sys.exit(main())
