#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test direct du service de surveillance"""
import sys
import io
# Force UTF-8 encoding for Windows console
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

import time
from ai_predictor import get_surveillance_service

print("[TEST] Recuperation du service...")
service = get_surveillance_service()

print(f"   - Service: {service is not None}")
print(f"   - is_running: {service.is_running}")
print(f"   - symbols_to_watch: {len(service.symbols_to_watch) if service.symbols_to_watch else 0}")
print(f"   - klines_fetcher: {service.klines_fetcher is not None}")

# Configurer si nécessaire
if not service.klines_fetcher:
    print("\n[WARN] klines_fetcher manquant, configuration...")
    from binance_api import BinanceAPI
    client = BinanceAPI()
    def fetch_klines(symbol, interval, limit):
        return client.get_klines_production(symbol, interval, limit)
    service.set_klines_fetcher(fetch_klines)
    print("   [OK] klines_fetcher configure")

if not service.symbols_to_watch:
    print("\n[WARN] symbols_to_watch vide, chargement watchlist...")
    import json
    with open('watchlist.json', 'r') as f:
        wl_data = json.load(f)
    service.set_symbols(wl_data.get('symbols', []))
    print(f"   [OK] {len(service.symbols_to_watch)} symboles charges")

print(f"\n[START] Demarrage du service...")
print(f"   - Avant start(): is_running={service.is_running}")

service.start()

print(f"   - Apres start(): is_running={service.is_running}")
print(f"   - Thread: {service._thread}")
print(f"   - Thread alive: {service._thread.is_alive() if service._thread else 'No thread'}")

print("\n[WAIT] Attente 30 secondes pour observer les cycles...")
for i in range(6):
    time.sleep(5)
    print(f"   {(i+1)*5}s - Thread alive: {service._thread.is_alive() if service._thread else 'No thread'}")

print("\n[DONE] Test termine")
