#!/usr/bin/env python3
"""
╔══════════════════════════════════════════════════╗
║   Reagent Tracker — Local Agent                  ║
║   The Miracle                                    ║
╚══════════════════════════════════════════════════╝

Legge i log di gioco in tempo reale e li invia al server.
Il server salva le raccolte solo quando premi Registra su una zona.

CONFIGURAZIONE:
  1. Incolla il tuo API Token (disponibile nella pagina "Importa & Agent")
  2. Verifica che LOGS_DIR punti alla cartella JournalLogs del tuo gioco
  3. Esegui: python3 local_agent.py
"""

import re
import sys
import time
import requests
from datetime import datetime
from pathlib import Path

# ─── CONFIGURAZIONE ───────────────────────────────────────────────────────────
SERVER_URL = "https://f-hackthesystem.club"   # URL del server (senza / finale)
API_TOKEN  = "INCOLLA_QUI_IL_TUO_TOKEN"       # Token dalla pagina Agent

# Percorso cartella log (modifica se necessario)
# Windows: r"C:\Users\TUO_NOME\AppData\Roaming\The Miracle\JournalLogs"
# macOS:   "/Applications/The Miracle.app/Contents/MacOS/Data/Client/JournalLogs"
LOGS_DIR = "/Applications/The Miracle.app/Contents/MacOS/Data/Client/JournalLogs"
# ─────────────────────────────────────────────────────────────────────────────

REAGENT_PATTERN = re.compile(r'\[(\d{2}/\d{2}/\d{4} \d{2}:\d{2})\]\s+Sistema: Hai raccolto : (\d+) (.+)')

HEADERS = {'X-Agent-Token': API_TOKEN, 'Content-Type': 'application/json'}


def log(msg):
    print(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}")


def latest_log(logs_path):
    """Restituisce il file journal più recente nella cartella, indipendentemente dalla data."""
    files = sorted(Path(logs_path).glob('*_journal.txt'))
    return files[-1] if files else None


def send(item):
    """Invia una raccolta al server. Restituisce il risultato o None in caso di errore."""
    try:
        r = requests.post(
            f"{SERVER_URL}/api/agent/collect",
            headers=HEADERS,
            json=[item],
            timeout=15
        )
        return r.json()
    except requests.exceptions.ConnectionError:
        log("  Errore: impossibile connettersi al server. Riprovo tra 10s...")
        time.sleep(10)
        return None
    except Exception as e:
        log(f"  Errore invio: {e}")
        return None


def check_token():
    """Verifica che il token sia valido."""
    if API_TOKEN == "INCOLLA_QUI_IL_TUO_TOKEN":
        print("\n╔══════════════════════════════════════════════════════╗")
        print("║  ERRORE: API Token non configurato!                  ║")
        print("║                                                      ║")
        print("║  1. Apri il sito Reagent Tracker                     ║")
        print("║  2. Vai su 'Importa & Agent' → sezione Agent         ║")
        print("║  3. Copia il tuo Token                               ║")
        print("║  4. Incollalo in questo script (riga API_TOKEN)      ║")
        print("╚══════════════════════════════════════════════════════╝\n")
        sys.exit(1)
    try:
        r = requests.post(f"{SERVER_URL}/api/agent/collect",
                          headers=HEADERS, json=[], timeout=5)
        if r.status_code == 401:
            print("\nERRORE: Token non valido. Controlla il token nella pagina Agent.\n")
            sys.exit(1)
        log("Token valido. Connessione al server OK.")
    except Exception as e:
        log(f"Impossibile raggiungere {SERVER_URL}: {e}")
        sys.exit(1)


def tail_log():
    """Monitora in tempo reale il log più recente, senza mai switchare file a mezzanotte."""
    logs_path = Path(LOGS_DIR)

    while True:
        fpath = latest_log(logs_path)

        if not fpath:
            log("In attesa di un file journal...")
            time.sleep(5)
            continue

        log(f"In ascolto: {fpath.name}")
        try:
            with open(fpath, 'r', encoding='utf-8', errors='replace') as f:
                f.seek(0, 2)  # salta alla fine del file
                while True:
                    line = f.readline()
                    if not line:
                        time.sleep(0.3)
                        continue

                    rm = REAGENT_PATTERN.search(line)
                    if rm:
                        ts       = datetime.strptime(rm.group(1), '%m/%d/%Y %H:%M').isoformat()
                        quantity = int(rm.group(2))
                        reagent  = rm.group(3).strip()
                        result   = send({
                            'timestamp': ts,
                            'reagent':   reagent,
                            'quantity':  quantity,
                        })
                        if result and result.get('stored'):
                            log(f"  ⏺ +{quantity}x {reagent}  [{result.get('zone', '')}]")
        except KeyboardInterrupt:
            log("Agente fermato.")
            sys.exit(0)
        except Exception as e:
            log(f"Errore: {e}. Riprovo tra 3s...")
            time.sleep(3)


if __name__ == '__main__':
    print("╔══════════════════════════════════════════════════╗")
    print("║   Reagent Tracker — Local Agent                  ║")
    print("╚══════════════════════════════════════════════════╝")
    print(f"  Server:   {SERVER_URL}")
    print(f"  Log dir:  {LOGS_DIR}")
    print()

    check_token()
    tail_log()
