"""Test 1-3 ISOLATI: regime detector, blocco orario, anti-cluster-loss.
NON usa il runner. Testa solo i moduli in isolamento.
"""
import os
import sys
import time
import json
from datetime import datetime, timezone, time as dtime
from pathlib import Path

V2_DIR = "/opt/charter-live/live_deploy_v2"
sys.path.insert(0, V2_DIR)

# Import moduli
os.chdir(V2_DIR)
import regime_detector
import anti_cluster_loss
import importlib.util
spec = importlib.util.spec_from_file_location("v2_runner", os.path.join(V2_DIR, "rettangolo_runner.py"))

print("=" * 70)
print("TEST 1: REGIME DETECTOR")
print("=" * 70)

# Stato iniziale
print("\n[1.1] Stato iniziale:")
print(f"  is_panic() = {regime_detector.is_panic()}")
state = regime_detector.get_state()
print(f"  state: {state}")

# Simula "panic" scrivendo manualmente regime_state.json
print("\n[1.2] Simulo PANIC: scrivo regime_state.json con panic_until = now+1h")
state_file = Path("/opt/charter-live/live_deploy_v2/logs/regime_state.json")
backup_file = Path("/opt/charter-live/live_deploy_v2/logs/regime_state.json.bak_test")
if state_file.exists():
    backup_file.write_text(state_file.read_text())
    print(f"  backup originale -> {backup_file}")

future_panic = time.time() + 3600
new_state = {
    "panic_until": future_panic,
    "last_check": time.time(),
    "last_4h_chg": {"BTCUSDT": -0.030, "ETHUSDT": -0.025},
    "last_24h_chg": {"BTCUSDT": -0.045, "ETHUSDT": -0.060},
    "panic_reason": "BTC 4h=-3.0% (<-2.5%), ETH 24h=-6.0% (<-5%)"
}
state_file.write_text(json.dumps(new_state, indent=2))
print(f"  scritto panic_until = {datetime.fromtimestamp(future_panic, tz=timezone.utc).isoformat()}")

# Verifica is_panic
importlib.reload(regime_detector)
is_panic = regime_detector.is_panic()
print(f"\n[1.3] is_panic() dopo setup = {is_panic}")
if is_panic:
    print("  ✅ TEST 1 PASS: regime_detector rileva panic")
else:
    print("  ❌ TEST 1 FAIL: regime_detector NON rileva panic")

# Cleanup: ripristina stato originale
if backup_file.exists():
    state_file.write_text(backup_file.read_text())
    backup_file.unlink()
    print(f"  stato originale ripristinato")

print()
print("=" * 70)
print("TEST 2: BLOCCO ORARIO (04:00-14:59)")
print("=" * 70)

# Importa is_blocked_hour
# E' in rettangolo_runner.py, devo caricarlo
runner_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(runner_module)

# Verifica logica is_blocked_hour
def is_blocked_hour_test(hour):
    """Replica la logica di is_blocked_hour dal runner v2."""
    return runner_module.BLOCK_HOURS_START <= hour <= runner_module.BLOCK_HOURS_END

print(f"\n[2.1] BLOCK_HOURS_START={runner_module.BLOCK_HOURS_START}, BLOCK_HOURS_END={runner_module.BLOCK_HOURS_END}")
print("\n[2.2] Test is_blocked_hour su tutte le 24 ore:")
print(f"  {'ORA':<8s} {'BLOCKED':<10s} {'ATTESO':<10s}")
all_pass = True
for h in range(24):
    blocked = is_blocked_hour_test(h)
    expected_block = 4 <= h <= 14
    status = "OK" if blocked == expected_block else "❌FAIL"
    if blocked != expected_block:
        all_pass = False
    print(f"  {h:02d}:00  {str(blocked):<10s} {str(expected_block):<10s} {status}")

if all_pass:
    print(f"\n  ✅ TEST 2 PASS: is_blocked_hour blocca correttamente 04:00-14:59, lascia passare 15:00-03:59")
else:
    print(f"\n  ❌ TEST 2 FAIL: logica is_blocked_hour sbagliata")

# Test specifico orario attuale (Europe/Rome)
from zoneinfo import ZoneInfo
LOCAL_TZ = ZoneInfo("Europe/Rome")
now_local = datetime.now(timezone.utc).astimezone(LOCAL_TZ)
current_h = now_local.hour
print(f"\n[2.3] Orario attuale Europe/Rome: {now_local.strftime('%H:%M')} (hour={current_h})")
print(f"  is_blocked_hour(now) = {is_blocked_hour_test(current_h)}")

print()
print("=" * 70)
print("TEST 3: ANTI-CLUSTER-LOSS")
print("=" * 70)

# Stato iniziale
print("\n[3.1] Stato iniziale:")
state = anti_cluster_loss.get_state()
print(f"  state: {state}")

# Simula 1 SL su BTCUSDT
print("\n[3.2] Simula 1 SL su BTCUSDT:")
anti_cluster_loss.record_sl('BTCUSDT')
state = anti_cluster_loss.get_state()
print(f"  state dopo 1 SL: {state.get('symbols', {}).get('BTCUSDT')}")
print(f"  should_pause('BTCUSDT') = {anti_cluster_loss.should_pause('BTCUSDT')} (atteso: False)")

# Simula 2 SL su BTCUSDT
print("\n[3.3] Simula 2° SL su BTCUSDT (dovrebbe triggerare pausa):")
anti_cluster_loss.record_sl('BTCUSDT')
state = anti_cluster_loss.get_state()
print(f"  state dopo 2 SL: {state.get('symbols', {}).get('BTCUSDT')}")
should_pause = anti_cluster_loss.should_pause('BTCUSDT')
print(f"  should_pause('BTCUSDT') = {should_pause} (atteso: True)")
if should_pause:
    print("  ✅ TEST 3 PASS: 2 SL consecutivi triggerano pausa 4h")
else:
    print("  ❌ TEST 3 FAIL: should_pause NON ritorna True dopo 2 SL")

# Test su altro symbol (non paused)
print("\n[3.4] Test su altro symbol (ETHUSDT, non paused):")
print(f"  should_pause('ETHUSDT') = {anti_cluster_loss.should_pause('ETHUSDT')} (atteso: False)")

# Reset stato anti_cluster_loss (rimuoviamo BTCUSDT per cleanup)
print("\n[3.5] Cleanup: reset anti_cluster_loss state")
state_file = Path("/opt/charter-live/live_deploy_v2/logs/anti_cluster_state.json")
if state_file.exists():
    # Mantengo ETHUSDT, rimuovo BTCUSDT
    state = anti_cluster_loss.get_state()
    if 'BTCUSDT' in state.get('symbols', {}):
        del state['symbols']['BTCUSDT']
    state_file.write_text(json.dumps(state, indent=2))
    print(f"  BTCUSDT rimosso da anti_cluster_state, ETHUSDT (e altri) preservati")
print(f"  state finale: {anti_cluster_loss.get_state()}")

print()
print("=" * 70)
print("RIEPILOGO")
print("=" * 70)
print("Test 1 (regime detector): vedi sopra")
print("Test 2 (blocco orario): vedi sopra")
print("Test 3 (anti-cluster-loss): vedi sopra")
