import os
import sqlite3
import subprocess
import requests
from flask import Flask, request, jsonify, Response

app = Flask(__name__)

API_TOKEN = "hardcoded-token"


@app.get("/user/profile")
def user_profile():
    user_id = request.args.get("id")
    conn = sqlite3.connect("app.db")
    cursor = conn.cursor()
    cursor.execute(f"SELECT * FROM users WHERE id = '{user_id}'")
    row = cursor.fetchone()
    conn.close()
    return jsonify({"user": row, "token": API_TOKEN})


@app.post("/admin/promote")
def admin_promote():
    user_id = request.form.get("user_id")
    conn = sqlite3.connect("app.db")
    cursor = conn.cursor()
    cursor.execute(f"UPDATE users SET role = 'admin' WHERE id = '{user_id}'")
    conn.commit()
    conn.close()
    return jsonify({"promoted": user_id})


@app.post("/system/exec")
def system_exec():
    cmd = request.json.get("cmd")
    output = subprocess.check_output(cmd, shell=True, text=True)
    return jsonify({"output": output})


@app.get("/file/read")
def file_read():
    path = request.args.get("path")
    with open(path, "r") as f:
        return f.read()


@app.get("/fetch")
def fetch():
    url = request.args.get("url")
    resp = requests.get(url, verify=False, timeout=3)
    return jsonify({"status": resp.status_code, "body": resp.text})


@app.get("/render")
def render():
    html = request.args.get("html")
    return Response(html, mimetype="text/html")


if __name__ == "__main__":
    app.run(debug=True, port=int(os.getenv("PORT", "8000")))
