# setup_nlp.py
import importlib
import importlib.metadata
import subprocess
import sys
import time


# pip distribution name : Python import name
PACKAGES = {
    "click==8.2.1": "click",
    "spacy": "spacy",
    "transformers": "transformers",
    "torch": "torch",
    "huggingface_hub": "huggingface_hub",
    "nltk": "nltk",
    "scikit-learn": "sklearn",
    "contractions": "contractions",
    "gensim": "gensim",
}

SPACY_MODELS = [
    "en_core_web_sm",
]

HF_MODELS = [
    "google-bert/bert-base-uncased"
]

# NLTK resource lookup paths : downloader package names
NLTK_RESOURCES = {
    "tokenizers/punkt": "punkt",
    "tokenizers/punkt_tab": "punkt_tab",
    "taggers/averaged_perceptron_tagger": "averaged_perceptron_tagger",
    "taggers/averaged_perceptron_tagger_eng": "averaged_perceptron_tagger_eng",
    "corpora/wordnet": "wordnet",
}

MAX_ATTEMPTS = 6
RETRY_WAIT_SECONDS = 3

HF_MAX_ATTEMPTS = 12
HF_RETRY_WAIT_SECONDS = 3
HF_SNAPSHOT_PATHS = {}


def heading(text):
    print(f"\n{'=' * 12} {text} {'=' * 12}", flush=True)


def retry_command(command):
    for attempt in range(1, MAX_ATTEMPTS + 1):
        print(
            f"[RUN] Attempt {attempt}/{MAX_ATTEMPTS}: {' '.join(command)}",
            flush=True,
        )
        try:
            subprocess.run(command, check=True)
            return True
        except subprocess.CalledProcessError as exc:
            print(f"[ERROR] Command exited with status {exc.returncode}.", flush=True)
            if attempt == MAX_ATTEMPTS:
                return False

            print(f"[RETRY] Waiting {RETRY_WAIT_SECONDS} seconds...", flush=True)
            time.sleep(RETRY_WAIT_SECONDS)

    return False


def package_is_installed(distribution):
    # Handle version-pinned entries such as click==8.2.1.
    name = distribution.split("==", 1)[0]

    try:
        installed_version = importlib.metadata.version(name)
        required_version = (
            distribution.split("==", 1)[1]
            if "==" in distribution
            else None
        )

        if required_version and installed_version != required_version:
            return False, installed_version

        return True, installed_version
    except importlib.metadata.PackageNotFoundError:
        return False, None


def check_packages():
    heading("STEP 1: PACKAGE IMPORT CHECKS")
    results = {}

    for distribution, module_name in PACKAGES.items():
        installed, installed_version = package_is_installed(distribution)

        try:
            importlib.import_module(module_name)
            if installed:
                print(
                    f"[OK]      {module_name} imported "
                    f"(version {installed_version})"
                )
                results[distribution] = True
            else:
                print(
                    f"[WARNING] {module_name} imports, but {distribution} "
                    "is not at the requested version."
                )
                results[distribution] = False
        except Exception as exc:
            print(f"[MISSING] {module_name} import failed: {exc}")
            results[distribution] = False

    return results


def check_spacy_models():
    heading("STEP 2: LOCAL SPACY MODEL CHECK")

    try:
        spacy = importlib.import_module("spacy")
    except Exception as exc:
        print(f"[SKIP] Cannot check spaCy models until spaCy is installed: {exc}")
        return {model: False for model in SPACY_MODELS}

    results = {}
    for model in SPACY_MODELS:
        try:
            spacy.load(model)
            print(f"[OK]      {model} loads locally")
            results[model] = True
        except Exception as exc:
            print(f"[MISSING] {model} is not loadable locally: {exc}")
            results[model] = False

    return results


def check_hf_models():
    heading("STEP 3: LOCAL HUGGING FACE MODEL CHECK")
    results = {}

    try:
        from transformers import AutoConfig, AutoModel, AutoTokenizer
    except Exception as exc:
        print(
            "[SKIP] Cannot check Hugging Face models until transformers "
            f"is installed: {exc}"
        )
        return {model: False for model in HF_MODELS}

    for model_id in HF_MODELS:
        try:
            # Local-only: this check must not download anything.
            AutoConfig.from_pretrained(model_id, local_files_only=True)
            AutoTokenizer.from_pretrained(model_id, local_files_only=True)
            AutoModel.from_pretrained(model_id, local_files_only=True)
            print(
                f"[OK]      {model_id}: config, tokenizer, and weights "
                "load locally"
            )
            results[model_id] = True
        except Exception as exc:
            print(f"[MISSING] {model_id} is not fully loadable locally: {exc}")
            results[model_id] = False

    return results


def check_nltk_data():
    heading("STEP 4: LOCAL NLTK DATA CHECK")

    try:
        import nltk
    except Exception as exc:
        print(f"[SKIP] Cannot check NLTK data until nltk is installed: {exc}")
        return {resource: False for resource in NLTK_RESOURCES}

    results = {}

    for resource_path in NLTK_RESOURCES:
        try:
            nltk.data.find(resource_path)
            print(f"[OK]      {resource_path} is available locally")
            results[resource_path] = True
        except LookupError:
            print(f"[MISSING] {resource_path} is not available locally")
            results[resource_path] = False
        except Exception as exc:
            print(f"[MISSING] Could not check {resource_path}: {exc}")
            results[resource_path] = False

    # Also test the requested wordnet.synsets("test") call.
    try:
        from nltk.corpus import wordnet

        synsets = wordnet.synsets("test")
        print(f"[OK]      wordnet.synsets('test') returned {len(synsets)} results")
        results["wordnet.synsets('test')"] = True
    except LookupError as exc:
        print(f"[MISSING] wordnet.synsets('test') could not run: {exc}")
        results["wordnet.synsets('test')"] = False
    except Exception as exc:
        print(f"[FAIL] wordnet.synsets('test') failed: {exc}")
        results["wordnet.synsets('test')"] = False
    else:
        results["wordnet.synsets('test')"] = True

    return results


def install_missing_packages(package_results):
    heading("STEP 5: INSTALL OR REPAIR PACKAGES")

    missing = [
        distribution
        for distribution, available in package_results.items()
        if not available
    ]

    if not missing:
        print("[OK] All requested packages are installed and importable.")
        return True

    print(f"[INFO] Installing/updating: {', '.join(missing)}")
    return retry_command([
        sys.executable,
        "-m",
        "pip",
        "install",
        "--retries",
        "5",
        "--timeout",
        "30",
        *missing,
    ])


def download_missing_spacy_models(model_results):
    heading("STEP 6: DOWNLOAD MISSING SPACY MODELS")

    for model, available in model_results.items():
        if available:
            print(f"[SKIP] {model} already loads locally.")
            continue

        print(f"[INFO] Downloading {model}...")
        ok = retry_command([
            sys.executable,
            "-m",
            "spacy",
            "download",
            model,
        ])
        if not ok:
            print(f"[FAIL] Could not download {model} after retries.")


def download_missing_hf_models(model_results):
    heading("STEP 7: DOWNLOAD MISSING HUGGING FACE MODELS")

    try:
        from huggingface_hub import snapshot_download
    except Exception as exc:
        print(f"[FAIL] huggingface_hub is not available: {exc}")
        return

    for model_id, available in model_results.items():
        if available:
            print(f"[SKIP] {model_id} already loads locally.")
            continue

        for attempt in range(1, HF_MAX_ATTEMPTS + 1):
            try:
                print(
                    f"[RUN] Downloading {model_id}, "
                    f"attempt {attempt}/{HF_MAX_ATTEMPTS}",
                    flush=True,
                )

                local_path = snapshot_download(repo_id=model_id)
                HF_SNAPSHOT_PATHS[model_id] = local_path
                print(f"[OK] Snapshot downloaded to: {local_path}", flush=True)
                break

            except Exception as exc:
                print(
                    f"[ERROR] Download attempt failed: "
                    f"{type(exc).__name__}: {exc}"
                )

                if attempt == HF_MAX_ATTEMPTS:
                    print(f"[FAIL] Could not download {model_id} after retries.")
                    break

                print(
                    f"[RETRY] Waiting {HF_RETRY_WAIT_SECONDS} seconds...",
                    flush=True,
                )
                time.sleep(HF_RETRY_WAIT_SECONDS)


def download_missing_nltk_data(data_results):
    heading("STEP 8: DOWNLOAD MISSING NLTK DATA")

    try:
        import nltk
    except Exception as exc:
        print(f"[FAIL] Cannot download NLTK data until nltk is installed: {exc}")
        return

    for resource_path, package_name in NLTK_RESOURCES.items():
        if data_results.get(resource_path, False):
            print(f"[SKIP] {package_name} is already available.")
            continue

        print(f"[INFO] Downloading NLTK data package {package_name}...")
        try:
            succeeded = nltk.download(package_name, quiet=True)
            if succeeded:
                print(f"[OK] Downloaded {package_name}.")
            else:
                print(f"[FAIL] Could not download {package_name}.")
        except Exception as exc:
            print(f"[FAIL] Download of {package_name} failed: {exc}")


def verify_huggingface_models():
    heading("HUGGING FACE MODEL VERIFICATION")

    try:
        from transformers import AutoModel, AutoTokenizer
    except Exception as exc:
        print(f"[FAIL] Cannot import Transformers: {exc}")
        return {model_id: False for model_id in HF_MODELS}

    results = {}

    for model_id in HF_MODELS:
        # Prefer the exact directory returned by snapshot_download().
        model_location = HF_SNAPSHOT_PATHS.get(model_id, model_id)

        try:
            print(f"[INFO] Testing local files for {model_id}...", flush=True)
            tokenizer = AutoTokenizer.from_pretrained(
                model_location,
                local_files_only=True,
            )
            tokenizer("A quick tokenizer check.")

            AutoModel.from_pretrained(
                model_location,
                local_files_only=True,
            )

            print(
                f"[OK] {model_id}: tokenizer and model weights load locally."
            )
            results[model_id] = True
        except Exception as exc:
            print(
                f"[FAIL] {model_id}: {type(exc).__name__}: {exc}",
                flush=True,
            )
            results[model_id] = False

    return results


def verify_nltk():
    heading("NLTK DATA VERIFICATION")
    results = {}

    try:
        import nltk
        from nltk.corpus import wordnet
    except Exception as exc:
        print(f"[FAIL] Cannot import NLTK: {exc}")
        return {"nltk": False}

    for resource_path in NLTK_RESOURCES:
        try:
            nltk.data.find(resource_path)
            print(f"[OK] {resource_path} is available.")
            results[resource_path] = True
        except LookupError as exc:
            print(f"[FAIL] {resource_path} is unavailable: {exc}")
            results[resource_path] = False

    try:
        synsets = wordnet.synsets("test")
        print(f"[OK] wordnet.synsets('test') returned {len(synsets)} results.")
        results["wordnet.synsets('test')"] = True
    except Exception as exc:
        print(f"[FAIL] wordnet.synsets('test') failed: {exc}")
        results["wordnet.synsets('test')"] = False

    return results


def final_verification():
    heading("FINAL VERIFICATION")

    spacy_results = check_spacy_models()
    hf_results = verify_huggingface_models()
    nltk_results = verify_nltk()

    heading("SUMMARY")

    for model, available in spacy_results.items():
        print(f"{'[OK]' if available else '[FAIL]'} spaCy: {model}")

    for model, available in hf_results.items():
        print(f"{'[OK]' if available else '[FAIL]'} Hugging Face: {model}")

    for resource, available in nltk_results.items():
        print(f"{'[OK]' if available else '[FAIL]'} NLTK: {resource}")


if __name__ == "__main__":
    heading("NLP ENVIRONMENT SETUP")
    print(f"Python executable: {sys.executable}")

    package_results = check_packages()
    spacy_results = check_spacy_models()
    hf_results = check_hf_models()
    nltk_results = check_nltk_data()

    # Downloads and installations begin only after the initial checks are printed.
    if install_missing_packages(package_results):
        download_missing_spacy_models(spacy_results)
        download_missing_hf_models(hf_results)
        download_missing_nltk_data(nltk_results)
        final_verification()
    else:
        print(
            "\n[STOP] Package installation failed; model and data "
            "downloads were not started."
        )
        sys.exit(1)

