from flask import Flask, render_template, request, jsonify
from datetime import datetime
import os
import json
import math

app = Flask(__name__, template_folder='templates')  # Explicitní cesta

# Konfigurační soubory
VERIFY_CONFIG = "verify_config.json"
WELCOME_CONFIG = "welcome_config.json"

# Přidej konstanty pro soubory
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = os.path.join(BASE_DIR, 'ticket_config.json')
TICKETS_FILE = os.path.join(BASE_DIR, 'tickets_data.json')

# --- HELPERS ---
def load_config(filename):
    if not os.path.exists(filename):
        if filename == VERIFY_CONFIG:
            default = {
                "verify_channel_id": None,
                "verify_embed": {
                    "title": "✅ Ověření účtu",
                    "description": "Klikni na tlačítko níže pro ověření!",
                    "color": 5763719
                }
            }
        else:
            default = {
                "welcome_channel_id": None,
                "welcome_embed": {
                    "title": "Vítej na serveru, {user}!",
                    "description": "Přečti si pravidla v #pravidla",
                    "color": 2067276
                }
            }
        with open(filename, "w") as f:
            json.dump(default, f)
        return default
    with open(filename, "r") as f:
        return json.load(f)

def get_default_config():
    return {
        "enabled": True,
        "channel_id": None,
        "category_id": None,
        "support_role_id": None,
        "embed": {
            "title": "Vytvoření ticketu",
            "description": "Pro vytvoření ticketu klikněte na tlačítko níže.",
            "color": 5865242
        },
        "button": {
            "label": "Vytvořit ticket",
            "emoji": "🎫"
        }
    }

# --- WELCOME API ---
@app.route("/api/welcome", methods=["POST"])
def update_welcome_config():
    new_config = request.json
    with open(WELCOME_CONFIG, "w") as f:
        json.dump(new_config, f)
    return jsonify({"success": True})

@app.route("/api/welcome_config", methods=["GET"])
def get_welcome_config():
    return jsonify(load_config(WELCOME_CONFIG))

# --- VERIFY API ---
@app.route("/api/verify", methods=["POST"])
def update_verify_config():
    new_config = request.json
    with open("verify_config.json", "w") as f:
        json.dump(new_config, f)
    # Zápis signálu pro bota
    with open("verify_update.signal", "w") as f:
        f.write("update")
    return jsonify({"success": True})

@app.route("/api/verify_config", methods=["GET"])
def get_verify_config():
    return jsonify(load_config(VERIFY_CONFIG))

# --- PREFIX API ---
@app.route("/api/prefix", methods=["GET"])
def get_prefix():
    """Získání aktuálního prefixu"""
    prefix = os.getenv("PREFIX", "!")
    return jsonify({"prefix": prefix})

@app.route("/api/prefix", methods=["POST"])
def update_prefix():
    """Aktualizace prefixu"""
    new_prefix = request.json.get("prefix")
    if not new_prefix:
        return jsonify({"success": False, "error": "Prefix nemůže být prázdný"})
    
    # Uložení do .env souboru
    env_path = ".env"
    lines = []
    prefix_found = False
    
    if os.path.exists(env_path):
        with open(env_path, "r") as f:
            lines = f.readlines()
    
    # Aktualizuj nebo přidej PREFIX
    for i, line in enumerate(lines):
        if line.startswith("PREFIX="):
            lines[i] = f"PREFIX={new_prefix}\n"
            prefix_found = True
            break
    
    if not prefix_found:
        lines.append(f"PREFIX={new_prefix}\n")
    
    with open(env_path, "w") as f:
        f.writelines(lines)
    
    # Signál pro aktualizaci statusu
    with open("prefix_update.signal", "w") as f:
        f.write("update")
    
    return jsonify({"success": True, "message": "Prefix změněn okamžitě! 🎉"})

# --- MONITORING API ---
@app.route("/api/monitoring", methods=["GET"])
def get_monitoring_data():
    """Získání monitoring dat"""
    try:
        with open("monitoring_data.json", "r") as f:
            data = json.load(f)
        return jsonify(data)
    except FileNotFoundError:
        return jsonify({"error": "No monitoring data available"})

@app.route("/api/monitoring/config", methods=["GET"])
def get_monitoring_config():
    """Získání monitoring konfigurace"""
    try:
        with open("monitoring_config.json", "r") as f:
            config = json.load(f)
        return jsonify(config)
    except FileNotFoundError:
        return jsonify({
            "cpu_threshold": 80,
            "memory_threshold": 85,
            "disk_threshold": 90,
            "temp_threshold": 75,
            "alert_channel_id": None
        })

@app.route("/api/monitoring/config", methods=["POST"])
def update_monitoring_config():
    """Aktualizace monitoring konfigurace"""
    try:
        new_config = request.json
        with open("monitoring_config.json", "w") as f:
            json.dump(new_config, f, indent=2)
        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)})

@app.route("/api/monitoring/method", methods=["GET"])
def get_monitoring_method():
    """Získání způsobu měření"""
    try:
        with open("monitoring_config.json", "r") as f:
            config = json.load(f)
        return jsonify({
            "method": config.get("monitoring_method", "auto"),
            "system": config.get("system_override", "auto")
        })
    except FileNotFoundError:
        return jsonify({
            "method": "auto",
            "system": "auto"
        })

@app.route("/api/monitoring/method", methods=["POST"])
def update_monitoring_method():
    """Aktualizace způsobu měření"""
    try:
        new_method = request.json
        
        # Načti existující config
        config = {}
        if os.path.exists("monitoring_config.json"):
            with open("monitoring_config.json", "r") as f:
                config = json.load(f)
        
        # Přidej novou metodu
        config.update(new_method)
        
        with open("monitoring_config.json", "w") as f:
            json.dump(config, f, indent=2)
        
        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)})

@app.route('/api/monitoring/alert-channel', methods=['POST'])
def set_alert_channel():
    try:
        data = request.json
        channel_id = data.get('alert_channel_id')
        
        if not channel_id:
            return jsonify({'success': False, 'error': 'Channel ID is required'})
        
        # Validace Discord Channel ID
        if not channel_id.isdigit() or len(channel_id) < 17 or len(channel_id) > 19:
            return jsonify({'success': False, 'error': 'Invalid Discord Channel ID'})
        
        # Načti současnou konfiguraci
        config_file = "monitoring_config.json"
        if os.path.exists(config_file):
            with open(config_file, "r") as f:
                config = json.load(f)
        else:
            config = {}
        
        # Aktualizuj alert channel
        config['alert_channel_id'] = int(channel_id)
        
        # Uložení
        with open(config_file, "w") as f:
            json.dump(config, f, indent=2)
        
        print(f"✅ Alert channel saved: {channel_id}")  # Debug
        
        return jsonify({'success': True, 'message': 'Alert channel set successfully'})
        
    except Exception as e:
        print(f"❌ Error saving alert channel: {e}")  # Debug
        return jsonify({'success': False, 'error': str(e)})

# --- SERVER MANAGEMENT API ---
@app.route('/api/servers/add', methods=['POST'])
def add_server():
    try:
        data = request.json
        name = data.get('name')
        host = data.get('host')
        port = data.get('port', 5000)
        
        if not name or not host:
            return jsonify({'success': False, 'error': 'Name and host are required'})
        
        # Validace
        server_id = name.lower().replace(" ", "_")
        
        # Test připojení
        try:
            import requests
            url = f"http://{host}:{port}/api/monitoring"
            response = requests.get(url, timeout=5)
            if response.status_code != 200:
                return jsonify({'success': False, 'error': f'Server {host}:{port} neodpovídá!'})
        except Exception as e:
            return jsonify({'success': False, 'error': f'Chyba připojení: {str(e)}'})
        
        # Načti současnou konfiguraci
        config_file = "servers_config.json"
        if os.path.exists(config_file):
            with open(config_file, "r") as f:
                servers = json.load(f)
        else:
            servers = {}
        
        # Přidej nový server
        servers[server_id] = {
            "name": name,
            "host": host,
            "port": port,
            "enabled": True,
            "added_at": datetime.now().isoformat()
        }
        
        # Uložení
        with open(config_file, "w") as f:
            json.dump(servers, f, indent=2)
        
        return jsonify({'success': True, 'server_id': server_id})
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@app.route('/api/servers/list', methods=['GET'])
def list_servers():
    try:
        config_file = "servers_config.json"
        if os.path.exists(config_file):
            with open(config_file, "r") as f:
                data = json.load(f)
                
                # Zkontroluj strukturu souboru
                if isinstance(data, dict) and "servers" in data:
                    servers = data["servers"]  # Nová struktura
                else:
                    servers = data  # Stará struktura - přímo {}
        else:
            servers = {}
            with open(config_file, "w") as f:
                json.dump(servers, f, indent=2)
        
        return jsonify({'servers': servers})
        
    except Exception as e:
        print(f"❌ Error in list_servers: {e}")
        return jsonify({'error': str(e)})

@app.route('/api/servers/remove', methods=['POST'])
def remove_server():
    try:
        data = request.json
        server_id = data.get('server_id')
        
        if not server_id:
            return jsonify({'success': False, 'error': 'Server ID is required'})
        
        # Načti konfiguraci
        config_file = "servers_config.json"
        if os.path.exists(config_file):
            with open(config_file, "r") as f:
                servers = json.load(f)
        else:
            return jsonify({'success': False, 'error': 'No servers configured'})
        
        if server_id not in servers:
            return jsonify({'success': False, 'error': 'Server not found'})
        
        # Odstraň server
        del servers[server_id]
        
        # Uložení
        with open(config_file, "w") as f:
            json.dump(servers, f, indent=2)
        
        return jsonify({'success': True})
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@app.route('/api/monitoring/multi', methods=['GET'])
def multi_server_monitoring():
    try:
        # Lokální data
        local_data = None
        if os.path.exists("monitoring_data.json"):
            with open("monitoring_data.json", "r") as f:
                local_data = json.load(f)
        
        # Vzdálené servery
        remote_data = {}
        offline_servers = []
        
        config_file = "servers_config.json"
        if os.path.exists(config_file):
            with open(config_file, "r") as f:
                data = json.load(f)
                
                # Zkontroluj strukturu souboru stejně jako v list_servers
                if isinstance(data, dict) and "servers" in data:
                    servers = data["servers"]
                else:
                    servers = data
            
            # Pro každý server zkus získat data
            for server_id, server in servers.items():
                try:
                    # Zkontroluj že server má všechny potřebné klíče
                    if not isinstance(server, dict) or 'name' not in server or 'host' not in server:
                        print(f"❌ Invalid server config for {server_id}: {server}")
                        continue
                    
                    import requests
                    url = f"http://{server['host']}:{server.get('port', 5000)}/api/monitoring"
                    response = requests.get(url, timeout=5)
                    if response.status_code == 200:
                        data = response.json()
                        data['server_name'] = server['name']
                        data['server_id'] = server_id
                        remote_data[server_id] = data
                    else:
                        offline_servers.append(server['name'])
                except Exception as e:
                    print(f"Server {server.get('name', server_id)} offline: {e}")
                    offline_servers.append(server.get('name', server_id))
        
        return jsonify({
            'local': local_data,
            'remote': remote_data,
            'offline': offline_servers
        })
        
    except Exception as e:
        print(f"❌ Error in multi_server_monitoring: {e}")
        return jsonify({'error': str(e)})

# --- LEVELING API ---
@app.route("/api/leveling/config", methods=["GET"])
def get_leveling_config():
    """Získání leveling konfigurace"""
    try:
        with open("leveling_config.json", "r") as f:
            config = json.load(f)
        return jsonify(config)
    except FileNotFoundError:
        return jsonify({
            "enabled": True,
            "xp_per_message": 15,
            "xp_cooldown": 60,
            "level_up_channel": None,
            "level_roles": {},
            "blacklisted_channels": [],
            "multiplier_channels": {},
            "reset_on_leave": False,
            "level_up_message": "🎉 Gratulujeme {user}! Dosáhl jsi **Level {level}**! 🎊",
            "show_level_card": True
        })

@app.route("/api/leveling/config", methods=["POST"])
def update_leveling_config():
    """Aktualizace leveling konfigurace"""
    try:
        new_config = request.json
        with open("leveling_config.json", "w") as f:
            json.dump(new_config, f, indent=2)
        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)})

@app.route("/api/leveling/data", methods=["GET"])
def get_leveling_data():
    """Získání leveling dat"""
    try:
        with open("leveling_data.json", "r") as f:
            data = json.load(f)
        
        # Přidej calculated fields
        for user_id, user_data in data.items():
            xp = user_data.get("xp", 0)
            user_data["calculated_level"] = math.floor(0.1 * math.sqrt(xp)) if xp > 0 else 0
        
        return jsonify(data)
    except FileNotFoundError:
        return jsonify({})
    except Exception as e:
        return jsonify({"error": str(e)})

@app.route("/api/leveling/leaderboard", methods=["GET"])
def get_leveling_leaderboard():
    """Získání žebříčku"""
    try:
        with open("leveling_data.json", "r") as f:
            data = json.load(f)
        
        # Seřaď podle XP
        leaderboard = []
        for user_id, user_data in data.items():
            if user_data.get("xp", 0) > 0:
                leaderboard.append({
                    "user_id": user_id,
                    "xp": user_data.get("xp", 0),
                    "level": user_data.get("level", 0),
                    "messages": user_data.get("messages", 0)
                })
        
        leaderboard.sort(key=lambda x: x["xp"], reverse=True)
        
        return jsonify({"leaderboard": leaderboard[:50]})  # Top 50
        
    except FileNotFoundError:
        return jsonify({"leaderboard": []})

@app.route("/api/leveling/user/<user_id>", methods=["GET"])
def get_user_leveling_data(user_id):
    """Získání dat konkrétního uživatele"""
    try:
        with open("leveling_data.json", "r") as f:
            data = json.load(f)
        
        user_data = data.get(user_id, {
            "xp": 0,
            "level": 0,
            "messages": 0,
            "last_message": None
        })
        
        return jsonify(user_data)
        
    except FileNotFoundError:
        return jsonify({
            "xp": 0,
            "level": 0,
            "messages": 0,
            "last_message": None
        })

# --- TICKETS API ---
@app.route("/api/tickets/config", methods=["GET"])
def get_ticket_config():
    try:
        os.makedirs(os.path.dirname(CONFIG_FILE), exist_ok=True)
        
        if os.path.exists(CONFIG_FILE):
            with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                config = json.load(f)
            return jsonify(config)
        else:
            default_config = get_default_config()
            with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
                json.dump(default_config, f, indent=4)
            return jsonify(default_config)
    except Exception as e:
        print(f"Error loading ticket config: {e}")
        return jsonify(get_default_config())

@app.route("/api/tickets/config", methods=["POST"])
def save_ticket_config():
    try:
        os.makedirs(os.path.dirname(CONFIG_FILE), exist_ok=True)
        
        config = request.json
        with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=4)
        return jsonify({"success": True})
    except Exception as e:
        print(f"Error saving ticket config: {e}")
        return jsonify({"success": False, "error": str(e)})

@app.route("/api/tickets/active", methods=["GET"])
def get_active_tickets():
    try:
        if os.path.exists(TICKETS_FILE):
            with open(TICKETS_FILE, 'r', encoding='utf-8') as f:
                tickets_data = json.load(f)
            
            tickets = [{"id": ticket_id, **ticket_data} for ticket_id, ticket_data in tickets_data.items()]
            return jsonify({"success": True, "tickets": tickets})
        else:
            with open(TICKETS_FILE, 'w', encoding='utf-8') as f:
                json.dump({}, f)
            return jsonify({"success": True, "tickets": []})
    except Exception as e:
        print(f"Error loading tickets: {e}")
        return jsonify({"success": False, "error": str(e), "tickets": []})

@app.route("/api/tickets/stats", methods=["GET"])
def get_ticket_stats():
    try:
        if os.path.exists(TICKETS_FILE):
            with open(TICKETS_FILE, 'r', encoding='utf-8') as f:
                tickets_data = json.load(f)
            
            total = len(tickets_data)
            closed = sum(1 for _, ticket in tickets_data.items() if ticket.get('status') == 'closed')
            open_tickets = total - closed
            
            return jsonify({
                "success": True,
                "total": total,
                "closed": closed,
                "open": open_tickets,
                "avg_response_time": 0
            })
        else:
            return jsonify({
                "success": True,
                "total": 0,
                "closed": 0,
                "open": 0,
                "avg_response_time": 0
            })
    except Exception as e:
        print(f"Error getting ticket stats: {e}")
        return jsonify({"success": False, "error": str(e)})

@app.route("/api/tickets/panel", methods=["POST"])
def post_ticket_panel():
    try:
        # Vytvoř soubor s požadavkem pro bota
        panel_request_file = os.path.join(BASE_DIR, 'ticket_panel_request.json')
        with open(panel_request_file, 'w', encoding='utf-8') as f:
            json.dump({
                "action": "post_panel",
                "timestamp": datetime.now().isoformat()
            }, f, indent=4)
        
        return jsonify({"success": True, "message": "Požadavek na ticket panel byl odeslán! Bot by měl brzy vytvořit panel v nastaveném kanálu."})
    except Exception as e:
        print(f"Error creating panel request: {e}")
        return jsonify({"success": False, "error": str(e)})

@app.route("/api/tickets/view/<ticket_id>", methods=["GET"])
def view_ticket(ticket_id):
    try:
        if os.path.exists(TICKETS_FILE):
            with open(TICKETS_FILE, 'r', encoding='utf-8') as f:
                tickets_data = json.load(f)
            
            if ticket_id in tickets_data:
                ticket = tickets_data[ticket_id]
                return jsonify({"id": ticket_id, **ticket})
            else:
                return jsonify({"success": False, "error": "Ticket nenalezen"})
        else:
            return jsonify({"success": False, "error": "Žádné tickety neexistují"})
    except Exception as e:
        print(f"Error viewing ticket: {e}")
        return jsonify({"success": False, "error": str(e)})

@app.route("/api/tickets/close/<ticket_id>", methods=["POST"])
def close_ticket(ticket_id):
    return jsonify({"success": True})

@app.route("/api/tickets/reopen/<ticket_id>", methods=["POST"])
def reopen_ticket(ticket_id):
    return jsonify({"success": True})

# --- WEB ROUTES ---
@app.route("/") 
def admin_panel():
    return render_template("index.html")



if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)