from flask import Flask, render_template, request, jsonify
import sys
import os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from ana_assistant.core.llm import LLM
from ana_assistant.core.system_control import SystemControl

app = Flask(__name__)

llm = LLM(provider="ollama")
sys_control = SystemControl()


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/api/chat", methods=["POST"])
def chat():
    data = request.json
    message = data.get("message", "")

    try:
        response = llm.ask(message)
        return jsonify({"response": response})
    except Exception as e:
        return jsonify({"response": f"Error: {str(e)}"})


@app.route("/api/stats")
def stats():
    try:
        cpu = sys_control.get_cpu_info()["cpu_percent"]
        ram = sys_control.get_memory_info()["percent"]
        disk = (
            sys_control.get_disk_info()[0]["percent"]
            if sys_control.get_disk_info()
            else 0
        )
        return jsonify({"cpu": int(cpu), "ram": int(ram), "disk": int(disk)})
    except:
        return jsonify({"cpu": 0, "ram": 0, "disk": 0})


if __name__ == "__main__":
    print("Starting Ana Web Interface...")
    print("Open http://localhost:5000 in your browser")
    app.run(host="0.0.0.0", port=5000, debug=True)
