import os
import requests
import zipfile
import time
from pathlib import Path


def download_openthesaurus(cache_dir = None) -> Path | None:

    if cache_dir is None:
        cache_dir = Path("./.cache")
    else:
        cache_dir = Path(cache_dir)

    # Define paths
    OPENTHESAURUS_URL = "https://www.openthesaurus.de/export/OpenThesaurus-Textversion.zip"
    OPENTHESAURUS_ZIP = cache_dir / "OpenThesaurus-Textversion.zip"
    OPENTHESAURUS_TXT = cache_dir / "openthesaurus.txt"

    if not OPENTHESAURUS_TXT.exists():
        if not OPENTHESAURUS_ZIP.exists():
            print("Downloading OpenThesaurus...")
            r = requests.get(OPENTHESAURUS_URL)
            with open(OPENTHESAURUS_ZIP, "wb") as f:
                f.write(r.content)
    
        print("Extracting...")
        with zipfile.ZipFile(OPENTHESAURUS_ZIP, 'r') as zip_ref:
            zip_ref.extractall(cache_dir)
    
    print(f"OpenThesaurus available at {OPENTHESAURUS_TXT}")

    return OPENTHESAURUS_TXT

