import requests
import time
import os
os.system("")

from neuralnet import NeuralNet
from symbolmanager import SymbolManager
from dashboard import print_dashboard
from datetime import datetime
from telegram_bot import send_telegram_message
from dbreader import load_data  # <-- NUOVO: lettura dal nuovo database

# Valori del ciclo precedente per le frecce ↑ ↓ →
previous_values = {}

# Memoria della direzione precedente per ogni simbolo
previous_state = {}

def log_inversion(symbol, long_p, short_p, neut_p, state, dominant_value, change_time, diff):
    with open("inversioni.txt", "a", encoding="utf-8") as f:
        if diff is not None:
            f.write(
                f"{symbol}  LONG={long_p:.3f}  SHORT={short_p:.3f}  NEUTRAL={neut_p:.3f}  "
                f"→ {state}=[{dominant_value:.3f}]  inversione alle {change_time}, diff={diff:+.3f}\n"
            )
        else:
            f.write(
                f"{symbol}  LONG={long_p:.3f}  SHORT={short_p:.3f}  NEUTRAL={neut_p:.3f}  "
                f"→ {state}=[{dominant_value:.3f}]  inversione alle {change_time}\n"
            )

def main():
    global previous_values, previous_state

    nn = NeuralNet()
    sm = SymbolManager()

    print("Avvio dashboard… (aggiornamento ogni 5 minuti)")

    try:
        while True:
            try:
                # 0) Carica i dati dal nuovo database (vecchie colonne: symbol, a, b, price)
                rows = load_data()  # deve restituire una lista di dict
                total_rows = len(rows)
                inversion_flags = {}

                # 1) Teniamo solo l’ultima riga per simbolo
                last_rows = {}
                for row in rows:
                    # row è un dict: {"symbol": ..., "a": ..., "b": ..., "price": ...}
                    last_rows[row['symbol']] = row

                results = {}

                # 2) Elaboriamo UNA sola riga per simbolo
                for symbol, row in last_rows.items():
                    out = nn.forward(row['a'], row['b'], row['price'], row['price'])

                    long_p  = float(out[0])
                    short_p = float(out[1])
                    neut_p  = float(out[2])

                    # Determina stato corrente
                    if short_p > long_p and short_p > neut_p:
                        current_state = "SHORT"
                        dominant_value = short_p
                    elif long_p > short_p and long_p > neut_p:
                        current_state = "LONG"
                        dominant_value = long_p
                    else:
                        current_state = "NEUTRAL"
                        dominant_value = neut_p

                    # 3) Verifica cambiamento significativo (threshold interno a SymbolManager)
                    state, changed, change_time, diff = sm.ensure(symbol, current_state, dominant_value)

                    # Recupera stato precedente PRIMA di aggiornarlo
                    prev_state = previous_state.get(symbol)

                    # Determina tipo di evento (solo inversione vera o forte continuità)
                    alert_type = None

                    # INVERSIONE vera: LONG ↔ SHORT
                    if prev_state in ("LONG", "SHORT") and current_state in ("LONG", "SHORT"):
                        if prev_state != current_state:
                            alert_type = "INVERSIONE"

                    # FORTE CONTINUITÀ: stessa direzione LONG/SHORT e rafforzamento significativo
                    if alert_type is None and prev_state == current_state and current_state in ("LONG", "SHORT"):
                        # soglia forza continuità: puoi regolarla, ora è 0.050
                        if diff is not None and abs(diff) >= 0.050:
                            alert_type = "FORTE_CONTINUITÀ"

                    # Aggiorna memoria stato (sempre, a fine decisione)
                    previous_state[symbol] = current_state

                    # 4) Gestione alert
                    if changed and alert_type == "INVERSIONE":
                        inversion_flags[symbol] = True

                        # Titolo = direzione attuale
                        title_direction = current_state  # LONG o SHORT

                        log_inversion(symbol, long_p, short_p, neut_p, state, dominant_value, change_time, diff)
                        print(f"{symbol}  → {title_direction} (inversione) [{dominant_value:.3f}]")

                        send_telegram_message(
                            f"📈 {symbol} — {title_direction} (inversione)\n"
                            f"LONG: {long_p:.3f}\n"
                            f"SHORT: {short_p:.3f}\n"
                            f"NEUTRAL: {neut_p:.3f}\n"
                            f"Dominante: {dominant_value:.3f}\n"
                            f"Diff: {diff:+.3f}\n"
                            f"Ora: {change_time}"
                        )

                    elif changed and alert_type == "FORTE_CONTINUITÀ":
                        inversion_flags[symbol] = True

                        # Titolo = direzione attuale
                        title_direction = current_state  # LONG o SHORT

                        print(f"{symbol}  → {title_direction} (continuità) ++ [{dominant_value:.3f}]")

                        send_telegram_message(
                            f"➡️ {symbol} — {title_direction} (continuità) ++\n"
                            f"LONG: {long_p:.3f}\n"
                            f"SHORT: {short_p:.3f}\n"
                            f"NEUTRAL: {neut_p:.3f}\n"
                            f"Dominante: {dominant_value:.3f}\n"
                            f"Diff: {diff:+.3f}\n"
                            f"Ora: {change_time}"
                        )

                    # Salva per dashboard
                    results[symbol] = [long_p, short_p, neut_p]

                # 5) Ordinamento dashboard
                sorted_results = dict(sorted(
                    results.items(),
                    key=lambda x: (-x[1][1], -x[1][0], x[0])
                ))

                # 6) Dashboard con frecce ↑ ↓ →
                print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Righe valide: {total_rows}")
                print_dashboard(sorted_results, previous_values, inversion_flags)

                # 7) Aggiorna i valori precedenti per le frecce
                previous_values = sorted_results.copy()

            except FileNotFoundError:
                # Questo ramo ormai servirà solo se lo userai ancora per qualcos'altro
                print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ERRORE: File CSV non trovato.")

            except Exception as e:
                print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ERRORE: {e}")

            print("In attesa di 5 minuti…")
            time.sleep(300)

    except KeyboardInterrupt:
        print("\nInterrotto manualmente. Chiusura pulita del programma.")

if __name__ == "__main__":
    main()
