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 collect_metrics():
    hostname = urlparse(URL).hostname

    # HTTP latency & uptime
    start = time.time()
    try:
        response = requests.get(URL, timeout=10)
        latency = round((time.time() - start) * 1000, 2)
        status = response.status_code
    except Exception:
        latency = -1
        status = 0

    # DNS lookup
    start = time.time()
    try:
        socket.gethostbyname(hostname)
        dns = round((time.time() - start) * 1000, 2)
    except Exception:
        dns = -1

    # SSL expiry
    ssl_expiry = "Unavailable"
    ssl_days = -1
    try:
        context = ssl.create_default_context()
        with socket.create_connection((hostname, 443), timeout=10) as sock:
            with context.wrap_socket(sock, server_hostname=hostname) as ssock:
                cert = ssock.getpeercert()

        expiry = datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
        ssl_expiry = expiry.strftime("%Y-%m-%d")
        ssl_days = (expiry - datetime.utcnow()).days
    except Exception:
        pass

    # Search response
    start = time.time()
    try:
        requests.get(URL, timeout=10)
        search_latency = round((time.time() - start) * 1000, 2)
    except Exception:
        search_latency = -1

    if os.path.exists(OUTPUT_FILE):
        with open(OUTPUT_FILE) as f:
            data = json.load(f)
    else:
        data = {"history": []}

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

    history.append({
        "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "status": status,
        "latency": latency,
        "dns": dns,
        "ssl_expiry": ssl_expiry,
        "ssl_days_left": ssl_days,
        "search_latency": search_latency
    })

    history = history[-1440:]

    uptime = round(
        len([x for x in history if x["status"] == 200]) /
        len(history) * 100,
        2
    )

    output = {
        "uptime": uptime,
        "last_check": history[-1],
        "history": history[-10:],
        "latency_chart": [x["latency"] for x in history[-60:]]
    }

    with open(OUTPUT_FILE, "w") as f:
        json.dump(output, f, indent=4)
