#!/usr/bin/env python3

"""
WiFi API Server - NEOG System
Serves real WiFi network data via REST API
Port: 9002 (NEOG Log Server uses 9001)
"""

import json
import subprocess
import time
from datetime import datetime
from flask import Flask, jsonify, request
from flask_cors import CORS
import threading

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

# Global cache
wifi_cache = {
    'data': None,
    'timestamp': 0,
    'scan_in_progress': False
}

CACHE_TTL = 5  # seconds
SWIFT_SCANNER_PATH = '/Users/neog/wifi-scanner.swift'

def run_wifi_scan():
    """Execute Swift WiFi scanner and return parsed JSON"""
    try:
        result = subprocess.run(
            ['swift', SWIFT_SCANNER_PATH],
            capture_output=True,
            text=True,
            timeout=15
        )

        if result.returncode == 0:
            try:
                data = json.loads(result.stdout)
                return data
            except json.JSONDecodeError as e:
                print(f"[ERROR] JSON decode failed: {e}")
                print(f"[DEBUG] Output: {result.stdout[:200]}")
                return {
                    'success': False,
                    'error': f'JSON parse error: {str(e)}',
                    'networks': []
                }
        else:
            print(f"[ERROR] Scanner failed: {result.stderr}")
            return {
                'success': False,
                'error': result.stderr or 'Scanner execution failed',
                'networks': []
            }

    except subprocess.TimeoutExpired:
        print("[ERROR] Scanner timeout")
        return {
            'success': False,
            'error': 'Scanner timeout (15s)',
            'networks': []
        }
    except Exception as e:
        print(f"[ERROR] Scan exception: {e}")
        return {
            'success': False,
            'error': str(e),
            'networks': []
        }

def get_wifi_networks(force_refresh=False):
    """Get WiFi networks with caching"""
    global wifi_cache

    current_time = time.time()

    # Return cached data if valid
    if not force_refresh and wifi_cache['data'] and (current_time - wifi_cache['timestamp']) < CACHE_TTL:
        cache_age = int(current_time - wifi_cache['timestamp'])
        print(f"[CACHE HIT] Age: {cache_age}s")
        wifi_cache['data']['cached'] = True
        wifi_cache['data']['cache_age'] = cache_age
        return wifi_cache['data']

    # Prevent concurrent scans
    if wifi_cache['scan_in_progress']:
        print("[SCAN] Already in progress, returning cached data")
        if wifi_cache['data']:
            wifi_cache['data']['cached'] = True
            return wifi_cache['data']
        return {
            'success': False,
            'error': 'Scan in progress',
            'networks': []
        }

    # Perform new scan
    wifi_cache['scan_in_progress'] = True
    print(f"[SCAN] Starting WiFi scan...")

    try:
        data = run_wifi_scan()
        data['cached'] = False
        data['cache_age'] = 0

        # Update cache
        wifi_cache['data'] = data
        wifi_cache['timestamp'] = current_time

        network_count = len(data.get('networks', []))
        print(f"[SCAN] Complete - Found {network_count} networks")

        return data

    finally:
        wifi_cache['scan_in_progress'] = False

# ============= API ROUTES =============

@app.route('/')
def index():
    """API info"""
    return jsonify({
        'service': 'NEOG WiFi API Server',
        'version': '1.0.0',
        'endpoints': {
            '/networks': 'GET - List all WiFi networks (cached)',
            '/scan': 'GET - Force new WiFi scan',
            '/status': 'GET - Server status',
            '/health': 'GET - Health check'
        },
        'port': 9002,
        'cache_ttl': f'{CACHE_TTL}s'
    })

@app.route('/networks', methods=['GET'])
def get_networks():
    """Get WiFi networks (uses cache if available)"""
    try:
        data = get_wifi_networks(force_refresh=False)
        return jsonify(data)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e),
            'networks': []
        }), 500

@app.route('/scan', methods=['GET'])
def force_scan():
    """Force a new WiFi scan (bypass cache)"""
    try:
        print("[API] Force scan requested")
        data = get_wifi_networks(force_refresh=True)
        return jsonify(data)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e),
            'networks': []
        }), 500

@app.route('/status', methods=['GET'])
def status():
    """Server status"""
    cache_valid = wifi_cache['data'] is not None
    cache_age = int(time.time() - wifi_cache['timestamp']) if wifi_cache['timestamp'] else None

    return jsonify({
        'server': 'running',
        'uptime': 'N/A',  # Would need to track start time
        'cache': {
            'valid': cache_valid,
            'age_seconds': cache_age,
            'ttl': CACHE_TTL,
            'network_count': len(wifi_cache['data'].get('networks', [])) if cache_valid else 0
        },
        'scan_in_progress': wifi_cache['scan_in_progress']
    })

@app.route('/health', methods=['GET'])
def health():
    """Health check endpoint"""
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.utcnow().isoformat()
    })

# ============= BACKGROUND TASKS =============

def auto_refresh_loop():
    """Background thread to refresh cache periodically"""
    print("[AUTO-REFRESH] Background thread started")
    while True:
        try:
            time.sleep(10)  # Wait 10 seconds between scans
            if not wifi_cache['scan_in_progress']:
                print("[AUTO-REFRESH] Triggering periodic scan")
                get_wifi_networks(force_refresh=True)
        except Exception as e:
            print(f"[AUTO-REFRESH] Error: {e}")

# ============= MAIN =============

if __name__ == '__main__':
    print("=" * 60)
    print("🌐 NEOG WiFi API Server")
    print("=" * 60)
    print(f"📡 Port: 9002")
    print(f"⏱️  Cache TTL: {CACHE_TTL}s")
    print(f"📁 Scanner: {SWIFT_SCANNER_PATH}")
    print(f"🔄 Auto-refresh: Every 10s")
    print("=" * 60)

    # Start background refresh thread
    refresh_thread = threading.Thread(target=auto_refresh_loop, daemon=True)
    refresh_thread.start()

    # Initial scan
    print("[INIT] Running initial WiFi scan...")
    initial_data = get_wifi_networks(force_refresh=True)
    if initial_data.get('success'):
        print(f"[INIT] Found {len(initial_data.get('networks', []))} networks")
    else:
        print(f"[INIT] Scan failed: {initial_data.get('error')}")

    print("\n🚀 Server starting on http://localhost:9002")
    print("📊 Access:")
    print("   - Networks: http://localhost:9002/networks")
    print("   - Force scan: http://localhost:9002/scan")
    print("   - Status: http://localhost:9002/status")
    print("\n" + "=" * 60 + "\n")

    # Run Flask server
    app.run(
        host='0.0.0.0',
        port=9002,
        debug=False,
        threaded=True
    )
