from flask import Blueprint, request, jsonify
import json
import os
from datetime import datetime

tickets_bp = Blueprint('tickets', __name__)

# Použít absolutní cesty místo relativních
BASE_DIR = os.path.dirname(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')

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": "🎫"
        }
    }

@tickets_bp.route('/config', methods=['GET'])
def get_ticket_config():
    try:
        # Ujistíme se, že adresář existuje
        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:
            # Vytvoříme výchozí konfiguraci
            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())

@tickets_bp.route('/config', methods=['POST'])
def save_ticket_config():
    try:
        # Ujistíme se, že adresář existuje
        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)})

@tickets_bp.route('/active', methods=['GET'])
def get_active_tickets():
    try:
        if os.path.exists(TICKETS_FILE):
            with open(TICKETS_FILE, 'r') as f:
                tickets_data = json.load(f)
            # Převést na seznam
            tickets = [{"id": ticket_id, **ticket_data} for ticket_id, ticket_data in tickets_data.items()]
            return jsonify({"success": True, "tickets": tickets})
        else:
            # Vytvoříme prázdný soubor ticketů
            with open(TICKETS_FILE, 'w') 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": []})

@tickets_bp.route('/stats', methods=['GET'])
def get_ticket_stats():
    try:
        if os.path.exists(TICKETS_FILE):
            with open(TICKETS_FILE, 'r') 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
            
            # Pro teď vrátíme zjednodušené statistiky
            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)})

@tickets_bp.route('/panel', methods=['POST'])
def post_ticket_panel():
    # Tato funkce bude volat Discord bota, zatím jen vrátíme success
    return jsonify({"success": True})

@tickets_bp.route('/view/<ticket_id>', methods=['GET'])
def view_ticket(ticket_id):
    try:
        if os.path.exists(TICKETS_FILE):
            with open(TICKETS_FILE, 'r') 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)})

@tickets_bp.route('/close/<ticket_id>', methods=['POST'])
def close_ticket(ticket_id):
    # Simulace uzavření ticketu
    return jsonify({"success": True})

@tickets_bp.route('/reopen/<ticket_id>', methods=['POST'])
def reopen_ticket(ticket_id):
    # Simulace znovu otevření ticketu
    return jsonify({"success": True})