import os
import random
import string
import requests
from datetime import datetime
from .hardware import HardwareManager

class LicenseKeys:
    def __init__(self, sheetID: str):
        self.sheet_url = f"https://docs.google.com/spreadsheets/d/{sheetID}/export?format=csv"
        self.getHwd = HardwareManager().get_hardware()

    def generate_license_key(self):
        chars = string.ascii_uppercase + string.digits
        raw = "".join(random.choice(chars) for _ in range(20))
        return "-".join(raw[i:i+4] for i in range(0, 20, 4))

    def generate_license_for_user(self):
        key = self.generate_license_key()
        return f"Key:{key} | HWD:{self.getHwd}"

    def validate_license_key(self, key: str) -> bool:
        try:
            resp = requests.get(self.sheet_url, timeout=10)
            resp.raise_for_status()
            lines = resp.text.splitlines()

            headers = [h.strip() for h in lines[0].split(",")]
            idx_hwid = headers.index("HWID")
            idx_name = headers.index("Username")
            idx_key = headers.index("Key")
            idx_exp = headers.index("Expiry")
            idx_status = headers.index("Status")

            for row in lines[1:]:
                cols = [c.strip() for c in row.split(",")]
                if len(cols) <= max(idx_hwid, idx_name, idx_key, idx_exp, idx_status):
                    continue

                if cols[idx_key] == key and cols[idx_hwid] == self.getHwd:
                    if cols[idx_status].lower() != "approved":
                        return False
                    try:
                        exp = datetime.fromisoformat(cols[idx_exp])
                        return datetime.now() <= exp
                    except Exception:
                        return False
            return False
        except Exception:
            return False

    def validate_local_license(self) -> bool:
        license_file = os.path.join(os.getcwd(), "license.txt")
        if not os.path.exists(license_file):
            return False

        content = open(license_file, encoding="utf-8").read().strip()
        parts = content.split("|")

        key = ""
        for p in parts:
            if p.strip().startswith("Key:"):
                key = p.replace("Key:", "").strip()

        if not key:
            return False

        return self.validate_license_key(key)

    def get_online_expiry_date(self):
        license_file = os.path.join(os.getcwd(), "license.txt")
        if not os.path.exists(license_file):
            return None

        content = open(license_file, encoding="utf-8").read().strip()
        parts = content.split("|")

        key = ""
        for p in parts:
            if p.strip().startswith("Key:"):
                key = p.replace("Key:", "").strip()

        if not key:
            return None

        try:
            resp = requests.get(self.sheet_url, timeout=10)
            resp.raise_for_status()
            lines = resp.text.splitlines()

            headers = [h.strip() for h in lines[0].split(",")]
            idx_hwid = headers.index("HWID")
            idx_name = headers.index("Username")
            idx_key = headers.index("Key")
            idx_exp = headers.index("Expiry")

            for row in lines[1:]:
                cols = [c.strip() for c in row.split(",")]
                if len(cols) <= max(idx_hwid, idx_name, idx_key, idx_exp):
                    continue

                if cols[idx_key] == key and cols[idx_hwid] == self.getHwd:
                    try:
                        return datetime.fromisoformat(cols[idx_exp])
                    except:
                        return None
        except Exception:
            return None

        return None