import requests
import socket
import ssl
import time
import json
import os
from datetime import datetime
from urllib.parse import urlparse

URL = "https://mithal.space"
OUTPUT_FILE = "metrics.json"


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

    try:
        r = requests.get(URL, timeout=10)
        latency = round((time.time() - start) * 1000, 2)
        return r.status_code, latency
    except:
        latency = round((time.time() - start) * 1000, 2)
        return 0, latency


def dns_lookup():
    host = urlparse(URL).hostname

    start = time.time()

    try:
        socket.gethostbyname(host)
    except:
        pass

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


def ssl_info():

    host = urlparse(URL).hostname

    try:

        ctx = ssl.create_default_context()

        with socket.create_connection((host,443),timeout=10) as sock:

            with ctx.wrap_socket(sock,server_hostname=host) as ssock:

                cert = ssock.getpeercert()

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

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

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

    except:

        return "Unavailable",-1


def search_response():

    start=time.time()

    try:
        requests.get(URL,timeout=10)
    except:
        pass

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


if os.path.exists(OUTPUT_FILE):

    with open(OUTPUT_FILE,"r") as f:

        data=json.load(f)

else:

    data={

        "history":[]

    }

status,latency=http_check()

record={

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

"status":status,

"latency":latency,

"dns":dns_lookup(),

"search_latency":search_response()

}

ssl_date,ssl_days=ssl_info()

record["ssl_expiry"]=ssl_date
record["ssl_days_left"]=ssl_days

data["history"].append(record)

if len(data["history"])>1440:

    data["history"]=data["history"][-1440:]

success=len([x for x in data["history"] if x["status"]==200])

uptime=round(success/len(data["history"])*100,2)

output={

"uptime":uptime,

"last_check":record,

"history":data["history"][-10:],

"latency_chart":[x["latency"] for x in data["history"][-60:]]

}

with open(OUTPUT_FILE,"w") as f:

    json.dump(output,f,indent=4)

print("="*40)
print("Mithal Monitoring")
print("="*40)
print("Status :",status)
print("Latency :",latency,"ms")
print("DNS :",record["dns"],"ms")
print("Search :",record["search_latency"],"ms")
print("SSL Expiry :",ssl_date)
print("Days Left :",ssl_days)
print("Uptime :",uptime,"%")
