#!/home/nonroot/update_xenforo_server_info/venv/bin/python3
from flask import Flask
from flask import request
from flask_cors import CORS
from werkzeug.middleware.proxy_fix import ProxyFix
import traceback
import json
from pprint import pprint
import a2s
from settings import ips, file_path

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1) 
CORS(app)

#AI slop
def get_player_list(ip, port):
    address = (ip, int(port))
    try:
        # Get player information
        players = a2s.players(address)
        
        player_data = []
        for p in players:
            player_data.append({
                "name": p.name,
                "score": p.score,
                "duration": p.duration # Seconds they've been online
            })
        return player_data
    except Exception as e:
        print(f"Error querying server: {e}")
        return []

#nginx used for reserve proxy
@app.route('/', methods = ['POST'])
def get_server_info():
    real_ip = request.headers.get('X-Real-IP', request.remote_addr)
    #ipv4 and ipv6 checks
    if real_ip != ips[0] and not real_ip.startswith(ips[1]):
        return "invalid"
    try:
        content = request.get_json()
        server_content = content["content"].split("###")
        del server_content[0] #removing # UNLOZE Server Info

        new_j = []
        for server in server_content:
            name = server.split("\n")[0].strip()
            map_ = server.split("**")[1].split(" ")[0]
            players = server.split("(")[1].split(")")[0]
            ip = server.split("\n[")[1].split("]")[0]
            d = get_player_list(ip.split(":")[0], ip.split(":")[1])
            j = {"name": name, "map": map_, "players": players, "ip": ip, "player_infos": d}
            new_j.append(j)

        #print(new_j)
        with open(file_path, 'w') as file:
            json.dump(new_j, file, ensure_ascii=False)
    except:
        err = traceback.format_exc()
        print("err: ", err)
    return ""

if __name__ == "__main__":
    from waitress import serve
    serve(app, host="127.0.0.1", port=5085, threads = 1)
