import logging
from flask import Flask, render_template, jsonify, request
from config import DEBUG, ZEROTIER_TOKEN
from zerotier_client import ZeroTierClient
from ping_service import PingService

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
zt_client = ZeroTierClient()
ping_service = PingService()

# Variabile globale per network_id
current_network_id = None

@app.route('/')
def home():
    """Pagina principale - dashboard"""
    return render_template('dashboard.html')

@app.route('/api/networks', methods=['GET'])
def get_networks():
    """Ritorna la lista delle reti ZeroTier connesse"""
    try:
        # ZeroTier API doesn't list networks directly, 
        # l'utente deve impostare manualmente il network_id
        return jsonify({
            'message': 'Use /api/nodes?network_id=<id> to get nodes',
            'example': '/api/nodes?network_id=xxxxxxxxxxxxxx'
        }), 200
    except Exception as e:
        logger.error(f'Error in get_networks: {e}')
        return jsonify({'error': str(e)}), 500

@app.route('/api/nodes', methods=['GET'])
def get_nodes():
    """Ritorna lo stato di tutti i nodi della rete"""
    global current_network_id
    
    try:
        network_id = request.args.get('network_id')
        
        if not network_id:
            return jsonify({'error': 'network_id parameter required'}), 400
        
        # Se è un network_id nuovo, avvia il servizio di ping
        if network_id != current_network_id:
            if ping_service.running:
                ping_service.stop()
            current_network_id = network_id
            ping_service.start(network_id)
        
        nodes = ping_service.get_nodes_status()
        
        return jsonify({
            'network_id': network_id,
            'total_nodes': len(nodes),
            'online_nodes': sum(1 for n in nodes if n['online']),
            'nodes': nodes
        }), 200
    except Exception as e:
        logger.error(f'Error in get_nodes: {e}')
        return jsonify({'error': str(e)}), 500

@app.route('/api/status', methods=['GET'])
def api_status():
    """Health check dell'API"""
    return jsonify({
        'status': 'ok',
        'zerotier_connected': zt_client.get_self() is not None
    }), 200

@app.before_request
def check_auth():
    """Verifica il token per le API"""
    # Se necessario aggiungere autenticazione
    pass

@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': 'Not found'}), 404

@app.errorhandler(500)
def internal_error(error):
    logger.error(f'Internal error: {error}')
    return jsonify({'error': 'Internal server error'}), 500

if __name__ == '__main__':
    try:
        logger.info('Starting ZeroCentral...')
        app.run(debug=DEBUG, host='0.0.0.0', port=5000)
    except KeyboardInterrupt:
        logger.info('Shutting down...')
        if ping_service.running:
            ping_service.stop()
