import argparse
import csv
import os
import re
import sys
import tempfile
import requests
from Bio import Entrez


def sanitize_scientific_name(name: str) -> str:
    """Strips strain, isolate, or specific culture tags from names for better GBIF matching."""
    cleaned = re.sub(
        r"\s+(sp\.|bacterium|strain|isolate|\d+.*|\([0-9]+\)).*",
        "",
        name,
        flags=re.IGNORECASE,
    )
    return cleaned.strip()


def resolve_taxid_to_name(tax_id: str, cache: dict) -> str | None:
    """Resolves NCBI TaxID to Scientific Name using an in-memory cache."""
    if tax_id in cache:
        return cache[tax_id]

    try:
        handle = Entrez.esummary(db="taxonomy", id=tax_id)
        summary = Entrez.read(handle)
        handle.close()
        if summary and "ScientificName" in summary[0]:
            name = summary[0]["ScientificName"]
            cache[tax_id] = name
            return name
    except Exception as e:
        print(f"Warning: Failed to fetch NCBI TaxID {tax_id}: {e}", file=sys.stderr)

    cache[tax_id] = None
    return None


def get_gbif_occurrence_count(
    scientific_name: str, country_code: str, cache: dict
) -> int | str:
    """
    Gets GBIF occurrence count for a scientific name in a target country.
    Returns integer count on success, or "UNKNOWN" on failure/unmatched.
    """
    if scientific_name in cache:
        return cache[scientific_name]

    names_to_try = [scientific_name]
    cleaned_name = sanitize_scientific_name(scientific_name)
    if cleaned_name and cleaned_name != scientific_name:
        names_to_try.append(cleaned_name)

    for name_query in names_to_try:
        try:
            match_url = f"https://api.gbif.org/v1/species/match?name={name_query}"
            resp = requests.get(match_url, timeout=10)

            if resp.status_code != 200:
                continue

            match_res = resp.json()

            # Ensure response is a dict before calling .get()
            if isinstance(match_res, dict):
                usage_key = match_res.get("usageKey")

                if usage_key:
                    occ_url = (
                        f"https://api.gbif.org/v1/occurrence/search"
                        f"?taxonKey={usage_key}&country={country_code}&limit=0"
                    )
                    occ_resp = requests.get(occ_url, timeout=10)

                    if occ_resp.status_code == 200:
                        occ_res = occ_resp.json()
                        if isinstance(occ_res, dict):
                            count = occ_res.get("count", 0)
                            cache[scientific_name] = count
                            return count
        except Exception as e:
            print(f"Warning: GBIF lookup error for '{name_query}': {e}", file=sys.stderr)
    cache[scientific_name] = "UNKNOWN"
    return "UNKNOWN"


def process_csv(csv_path: str, country_code: str = "IS"):
    """Reads CSV, adds occurrence count column, and overwrites the file safely."""
    taxid_cache = {}
    gbif_cache = {}

    target_header = "taxid_at_target_level"
    out_header = f"{country_code.lower()}_gbif_occurrence_count"

    dir_name = os.path.dirname(os.path.abspath(csv_path))

    with open(csv_path, mode="r", encoding="utf-8-sig") as infile:
        reader = csv.DictReader(infile)
        fieldnames = reader.fieldnames

        if not fieldnames or target_header not in fieldnames:
            print(
                f"Error: Could not find required header '{target_header}' in {csv_path}",
                file=sys.stderr,
            )
            sys.exit(1)

        new_fieldnames = list(fieldnames)
        if out_header not in new_fieldnames:
            new_fieldnames.append(out_header)

        with tempfile.NamedTemporaryFile(
            mode="w", delete=False, dir=dir_name, encoding="utf-8", newline=""
        ) as temp_file:
            writer = csv.DictWriter(temp_file, fieldnames=new_fieldnames)
            writer.writeheader()

            row_count = 0
            for row in reader:
                tax_id = row.get(target_header, "").strip()

                count: int | str = "UNKNOWN"
                if tax_id and tax_id.isdigit():
                    name = resolve_taxid_to_name(tax_id, taxid_cache)
                    if name:
                        count = get_gbif_occurrence_count(name, country_code, gbif_cache)

                row[out_header] = count
                writer.writerow(row)

                row_count += 1
                if row_count % 10 == 0:
                    print(f"Processed {row_count} rows...", end="\r", file=sys.stderr)

            temp_path = temp_file.name

    # Atomic swap: replace original file with updated temp file
    os.replace(temp_path, csv_path)
    print(f"\nDone! Successfully updated {row_count} rows in {csv_path}")


def main():
    parser = argparse.ArgumentParser(
        description="Append GBIF occurrence counts to a CSV containing 'taxid_at_target_level' and overwrite in place."
    )
    parser.add_argument("csv_file", type=str, help="Path to the input CSV file")
    parser.add_argument(
        "-c", "--country", type=str, default="IS", help="2-letter ISO country code (default: IS)"
    )
    parser.add_argument(
        "-e", "--email", type=str, default="user@example.com", help="Email required by NCBI Entrez API"
    )

    args = parser.parse_args()

    Entrez.email = args.email

    if not os.path.exists(args.csv_file):
        print(f"Error: File '{args.csv_file}' not found.", file=sys.stderr)
        sys.exit(1)

    process_csv(args.csv_file, country_code=args.country.upper())


if __name__ == "__main__":
    main()
