import os
import sys
import threading
import json
import argparse
from flask import Flask, request, jsonify
from app import HollowSteamBackend

backend = HollowSteamBackend()
server = Flask(__name__)

@server.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    return response

@server.before_request
def handle_options():
    if request.method == 'OPTIONS':
        return '', 204

@server.route('/api/search', methods=['POST', 'OPTIONS'])
def search():
    data = request.json
    query = data.get('query')
    backend.perform_search(query)
    return jsonify({"status": "searching"})

@server.route('/api/state', methods=['GET', 'OPTIONS'])
def get_state():
    state = {
        "log_output": backend.log_output,
        "search_results": backend._search_results,
        "current_app_id": backend.current_app_id,
        "current_game_name": backend.current_game_name,
        "current_depots_count": backend.current_depots_count,
        "current_dlcs_count": backend.current_dlcs_count,
        "add_to_steam_enabled": backend.add_to_steam_enabled,
        "add_to_cart_enabled": backend.add_to_cart_enabled,
        "cart_count": backend.cart_count,
        "is_searching": backend.is_searching,
        "is_fetching_details": backend.is_fetching_details
    }
    return jsonify(state)

@server.route('/api/cart', methods=['GET', 'OPTIONS'])
def get_cart():
    return jsonify(backend.cart)

@server.route('/api/settings', methods=['GET', 'POST', 'OPTIONS'])
def handle_settings():
    if request.method == 'POST':
        data = request.json
        backend._save_settings(data)
        return jsonify({"status": "saved"})
    else:
        settings_data = backend._load_settings()
        return jsonify(settings_data)

@server.route('/api/action', methods=['POST', 'OPTIONS'])
def perform_action():
    data = request.json
    action = data.get('action')
    if action == 'select_result':
        backend.select_result(data.get('index', 0))
    elif action == 'add_to_steam':
        backend.add_to_steam()
    elif action == 'add_to_cart':
        backend.on_add_to_cart_clicked()
    elif action == 'download_cart':
        backend.download_cart()
    elif action == 'clear_cart':
        backend.clear_cart()
    elif action == 'remove_from_cart':
        backend.remove_from_cart(str(data.get('app_id')))
    elif action == 'clear_search':
        backend.clear_search_results()
    return jsonify({"status": "ok"})

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Stratum Backend")
    parser.add_argument('--search', type=str, help='Search query to execute')
    parser.add_argument('--install', type=str, help='Install an app by ID or name')
    parser.add_argument('--toggle-additional-apps', action='store_true', help='Toggle whether to add games to SLS AdditionalApps')
    args, unknown = parser.parse_known_args()

    if args.search or args.install or args.toggle_additional_apps:
        if args.search:
            results = backend._sync_search(args.search)
            for r in results:
                print(f"{r['app_id']} - {r['title']}")
        if args.install:
            backend._sync_install(args.install)
        if args.toggle_additional_apps:
            backend._sync_toggle_additional_apps()
        sys.exit(0)

    server.run(host='127.0.0.1', port=5000, debug=False, use_reloader=False)
