#!/usr/bin/env python3
"""
Minecraft Chat Viewer - Flask Application
Production-ready Flask server for Docker/Coolify deployment
"""

from flask import Flask, send_from_directory, jsonify
import os

app = Flask(__name__)

# Configuration
PORT = int(os.environ.get('PORT', 5000))
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'minecraft-chat-viewer-secret-key')

# Base directory
BASE_DIR = os.path.dirname(os.path.abspath(__file__))


@app.route('/')
def index():
    """Serve the main HTML page"""
    return send_from_directory(BASE_DIR, 'index.html')


@app.route('/health')
def health():
    """Health check endpoint for Docker/Coolify"""
    return jsonify({
        'status': 'healthy',
        'service': 'minecraft-chat-viewer',
        'version': '1.0.0'
    }), 200


@app.route('/<path:filename>')
def serve_static(filename):
    """Serve static files (CSS, JS, etc.)"""
    return send_from_directory(BASE_DIR, filename)


@app.route('/chat-logs/<path:filename>')
def serve_chat_logs(filename):
    """Serve chat log files"""
    chat_logs_dir = os.path.join(BASE_DIR, 'chat-logs')
    return send_from_directory(chat_logs_dir, filename)


@app.errorhandler(404)
def not_found(e):
    """Custom 404 handler"""
    return jsonify({
        'error': 'File not found',
        'status': 404
    }), 404


@app.errorhandler(500)
def internal_error(e):
    """Custom 500 handler"""
    return jsonify({
        'error': 'Internal server error',
        'status': 500
    }), 500


if __name__ == '__main__':
    print(f"🎮 Minecraft Chat Viewer")
    print(f"📡 Starting Flask server on port {PORT}")
    print(f"📁 Base directory: {BASE_DIR}")
    print(f"🚀 Server ready at http://localhost:{PORT}")
    print(f"💚 Health check: http://localhost:{PORT}/health")
    print("-" * 60)
    
    # Run the Flask app
    app.run(
        host='0.0.0.0',
        port=PORT,
        debug=os.environ.get('FLASK_ENV') == 'development'
    )
