import json
import os
import socket
import ssl
import time
from datetime import datetime

import dns.resolver
import requests

URL = "https://mithal.space"
DATA_FILE = "data.json"


def get_dns_time():
    try:
        start = time.time()

        dns.resolver.resolve("mithal.space", "A")

        end = time.time()

        return round((end - start) * 1000, 2)

    except Exception:
        return None


def get_ssl_info():
    try:
        hostname = "mithal.space"

        context = ssl.create_default_context()

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

            sock.settimeout(10)
            sock.connect((hostname, 443))

            cert = sock.getpeercert()

            return {
                "valid": True,
                "expires": cert["notAfter"]
            }

    except Exception:

        return {
            "valid": False,
            "expires": None
        }


def get_search_response():
    try:
        start = time.time()

        requests.get(URL, timeout=10)

        end = time.time()

        return round((end - start) * 1000, 2)

    except Exception:
        return None


def check_website():
    try:
        response = requests.get(URL, timeout=10)

        result = {
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "status_code": response.status_code,
            "uptime": "UP" if response.status_code == 200 else "DOWN",
            "latency_ms": round(response.elapsed.total_seconds() * 1000, 2),
            "dns_ms": get_dns_time(),
            "search_response_ms": get_search_response(),
            "ssl": get_ssl_info()
        }

    except Exception as e:

        result = {
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "status_code": None,
            "uptime": "DOWN",
            "latency_ms": None,
            "dns_ms": None,
            "search_response_ms": None,
            "ssl": {
                "valid": False,
                "expires": None
            },
            "error": str(e)
        }

    return result


def load_data():
    if not os.path.exists(DATA_FILE):
        return []

    with open(DATA_FILE, "r") as file:
        try:
            return json.load(file)
        except json.JSONDecodeError:
            return []


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


def main():
    data = load_data()

    result = check_website()

    data.append(result)
    data = data[-10:]

    save_data(data)

    print(result)


if __name__ == "__main__":
    main()