from flask import Flask, render_template, jsonify
import requests
import os
from requests.auth import HTTPBasicAuth
from dotenv import load_dotenv

load_dotenv('/opt/adguard-dashboard/.env')

app = Flask(__name__)

ADGUARD_HOST = os.environ.get("ADGUARD_HOST")
ADGUARD_USER = os.environ.get("ADGUARD_USER")
ADGUARD_PASS = os.environ.get("ADGUARD_PASS")
EXCLUDE_CLIENTS = ["192.168.1.235"]

def get_tier(count):
    if count <= 500:
        return {"tier": 1, "label": "Innocent", "desc": "Blissfully unaware", "color": "#4ade80"}
    elif count <= 2000:
        return {"tier": 2, "label": "Rookie", "desc": "Starting to notice things", "color": "#facc15"}
    elif count <= 5000:
        return {"tier": 3, "label": "Protagonist", "desc": "Things are getting real", "color": "#fb923c"}
    elif count <= 9000:
        return {"tier": 4, "label": "Hardened Fighter", "desc": "Seen some things", "color": "#f87171"}
    else:
        return {"tier": 5, "label": "Final Boss", "desc": "Pure chaos energy", "color": "#c084fc"}


def get_client_names():
    try:
        resp = requests.get(
            f"{ADGUARD_HOST}/control/clients",
            auth=HTTPBasicAuth(ADGUARD_USER, ADGUARD_PASS),
            timeout=5
        )
        resp.raise_for_status()
        data = resp.json()
        lookup = {}
        for client in data.get("clients", []):
            for ip in client.get("ids", []):
                lookup[ip] = client["name"]
        return lookup
    except Exception:
        return {}


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


@app.route("/api/clients")
def clients():
    try:
        names = get_client_names()

        resp = requests.get(
            f"{ADGUARD_HOST}/control/stats",
            auth=HTTPBasicAuth(ADGUARD_USER, ADGUARD_PASS),
            timeout=5
        )
        resp.raise_for_status()
        data = resp.json()

        top_clients = data.get("top_clients", [])

        result = []
        for entry in top_clients:
            for ip, count in entry.items():
                if ip in EXCLUDE_CLIENTS:
                    continue
                tier_info = get_tier(count)
                result.append({
                    "name": names.get(ip, ip),
                    "ip": ip,
                    "blocks": count,
                    **tier_info
                })

        result.sort(key=lambda x: x["blocks"], reverse=True)
        return jsonify({"clients": result, "error": None})

    except requests.exceptions.ConnectionError:
        return jsonify({"clients": [], "error": "Could not connect to AdGuard Home"})
    except requests.exceptions.Timeout:
        return jsonify({"clients": [], "error": "AdGuard Home timed out"})
    except Exception as e:
        return jsonify({"clients": [], "error": str(e)})


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5001)
