import requests
import socket
import ssl
import json
import time
import threading
from datetime import datetime
from flask import Flask, jsonify, send_from_directory

app = Flask(__name__)

BASE_URL = "https://mithal.space"
SEARCH_URL = "https://mithal.space/search?q=test"

DATA_FILE = "monitor_data.json"

CHECK_INTERVAL = 60


def load_data():
    try:
        with open(DATA_FILE, "r") as f:
            return json.load(f)
    except:
        return []


def save_data(data):
    with open(DATA_FILE, "w") as f:
        json.dump(data, f, indent=4)


def get_latency():
    start = time.time()

    response = requests.get(BASE_URL, timeout=10)

    latency = round((time.time() - start) * 1000, 2)

    return latency, response.status_code


def get_dns_time():

    start = time.time()

    socket.gethostbyname("mithal.space")

    return round((time.time() - start) * 1000, 2)


def get_ssl_info():

    hostname = "mithal.space"

    context = ssl.create_default_context()

    with context.wrap_socket(
        socket.socket(),
        server_hostname=hostname
    ) as s:

        s.settimeout(10)

        s.connect((hostname, 443))

        cert = s.getpeercert()

    expiry = datetime.strptime(
        cert["notAfter"],
        "%b %d %H:%M:%S %Y %Z"
    )

    remaining = (expiry - datetime.utcnow()).days

    return expiry.strftime("%Y-%m-%d"), remaining


def get_search_latency():

    start = time.time()

    response = requests.get(
        SEARCH_URL,
        timeout=10
    )

    latency = round((time.time() - start) * 1000, 2)

    return latency, response.status_code

def monitor():

    while True:

        try:

            latency, status = get_latency()

            dns = get_dns_time()

            ssl_expiry, ssl_days = get_ssl_info()

            search_latency, search_status = get_search_latency()

            entry = {

                "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),

                "uptime": status == 200,

                "status_code": status,

                "latency_ms": latency,

                "dns_ms": dns,

                "ssl_expiry": ssl_expiry,

                "ssl_remaining_days": ssl_days,

                "search_latency_ms": search_latency,

                "search_status": search_status

            }

            data = load_data()

            data.append(entry)

            data = data[-1440:]

            save_data(data)

            print(entry)

        except Exception as e:

            print("Monitoring Error:", e)

        time.sleep(CHECK_INTERVAL)


@app.route("/api/data")
def api_data():

    return jsonify(load_data())


@app.route("/")
def home():

    return {
        "message": "Mithal Monitoring API",
        "dashboard": "/dashboard"
    }


@app.route("/dashboard")
def dashboard():

    return send_from_directory(".", "dashboard.html")


if __name__ == "__main__":

    thread = threading.Thread(target=monitor)

    thread.daemon = True

    thread.start()

    app.run(
        host="0.0.0.0",
        port=5002
    )
