from flask import Flask, send_file, jsonify
import threading
import time
import json
import os

from monitor import collect_metrics

app = Flask(__name__)


def monitor_loop():
    while True:
        try:
            collect_metrics()
            print("Metrics updated.")
        except Exception as e:
            print("Monitor error:", e)

        time.sleep(60)


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


@app.route("/metrics.json")
def metrics():
    if os.path.exists("metrics.json"):
        with open("metrics.json") as f:
            return jsonify(json.load(f))

    return jsonify({
        "uptime": 0,
        "last_check": {},
        "history": [],
        "latency_chart": []
    })


if __name__ == "__main__":
    # Run one check immediately
    collect_metrics()

    # Start background monitoring
    thread = threading.Thread(target=monitor_loop, daemon=True)
    thread.start()

    # Start Flask
    app.run(host="0.0.0.0", port=8080)
