import re
from . import assets_path, proj_path
from .utils import make_hash

hashes_fname = assets_path / "hashes.txt"
activated_hash_fname = assets_path / "activated_hash.txt"

key_pattern = re.compile(
    r"^[A-Z0-9]{4}-"
    r"[A-Z0-9]{4}-"
    r"[A-Z0-9]{4}-"
    r"J[A-Z0-9]{3}$"
)

def load_hashes() -> set[str]:
    with hashes_fname.open(encoding="utf-8") as f:
        return {
            line.strip()
            for line in f
            if line.strip()
        }

def load_activated_hash() -> str | None:

    if not activated_hash_fname.exists():
        return None

    hash_code = activated_hash_fname.read_text(encoding="utf-8").strip()

    if not hash_code:
        return None

    return hash_code

def valid_triplet(triplet: str) -> bool:

    hash_code = make_hash(triplet)

    activated_hash = load_activated_hash()

    if activated_hash:
        return hash_code == activated_hash

    hashes = load_hashes()

    if hash_code not in hashes:
        return False

    activated_hash_fname.write_text(hash_code, encoding="utf-8")
    return True

def valid_key(key: str) -> bool:

    if not key_pattern.fullmatch(key):
        return False

    triplet = key.rsplit("-", 1)[0]

    if not valid_triplet(triplet):
        return False

    s = key[:-1] + "X"
    last_char = make_hash(s, 1).upper()
    if last_char != key[-1]:
        return False

    key_fname = proj_path / "license_key.txt"
    key_fname.write_text(key, encoding="utf-8")

    return True
