import traceback

import pysam
from tqdm import tqdm

from util.db import (
    get_latin_names_batch,
    get_lineage_from_taxid,
    get_taxids_for_accessions,
)
from util.var import BATCH_SIZE, BUCKET_LIST, MAJOR_RANKS, TAXONOMY_ORDER


def tax_lump_batch_modified(taxids, target_tax_level, conn):
    lumped_taxid_map = {}

    for taxid in set(taxids):
        target_taxid, lineage = get_lineage_from_taxid(taxid, target_tax_level, conn)
        if target_taxid:
            lumped_taxid_map[taxid] = {
                "lineage": lineage,
                "target_tax_id": target_taxid,
            }
        else:
            lumped_taxid_map[taxid] = {"lineage": {}, "target_tax_id": "Other"}
    return lumped_taxid_map


def process_bam_optimized(input_file, tax_level, primary, conn):
    total_reads = 0
    if tax_level not in TAXONOMY_ORDER:
        print(f"[Error] Invalid taxonomic level: {tax_level}")
        return {}, 0, {}

    try:
        target_rank_index = MAJOR_RANKS.index(tax_level)
    except ValueError:
        print(
            f"[Warning] Target rank '{tax_level}' is not in MAJOR_RANKS list. Defaulting to 'genus'."
        )
        target_rank_index = MAJOR_RANKS.index("genus")

    taxid_cache = {}
    lumped_lineage_cache = {}

    # accession_batch stores tuples: (accession, ds_score, nm_score, as_score, xm_score)
    accession_batch = []

    counts_data = {}
    lineage_lookup = {}

    try:
        with pysam.AlignmentFile(input_file, "rb") as bamfile:
            for read in tqdm(
                bamfile.fetch(until_eof=True),
                unit=" Reads",
                unit_scale=True,
                desc="Parsing BAM file",
            ):
                # Filter out secondary and supplementary alignments if primary is True
                if primary and (read.is_secondary or read.is_supplementary):
                    continue

                total_reads += 1
                acc = read.reference_name

                # Extract the alignment tags carefully
                ds_score = None
                try:
                    ds_score = float(read.get_tag("DS"))
                except (KeyError, ValueError):
                    pass

                nm_score = None
                try:
                    nm_score = int(read.get_tag("NM"))
                except (KeyError, ValueError):
                    pass

                as_score = None
                try:
                    as_score = int(read.get_tag("AS"))
                except (KeyError, ValueError):
                    pass

                xm_score = None
                try:
                    xm_score = int(read.get_tag("XM"))
                except (KeyError, ValueError):
                    pass

                # Append all extracted values to the batch tuple
                accession_batch.append((acc, ds_score, nm_score, as_score, xm_score))

                if len(accession_batch) >= BATCH_SIZE:
                    process_batch(
                        accession_batch,
                        taxid_cache,
                        lumped_lineage_cache,
                        tax_level,
                        conn,
                        counts_data,
                        lineage_lookup,
                    )
                    accession_batch = []

    except FileNotFoundError:
        print(f"[Error] The file {input_file} was not found.")
        return {}, 0, {}
    except Exception as e:
        print(f"[Error] An unexpected error occurred: {e}")
        traceback.print_exc()
        return {}, 0, {}

    if accession_batch:
        process_batch(
            accession_batch,
            taxid_cache,
            lumped_lineage_cache,
            tax_level,
            conn,
            counts_data,
            lineage_lookup,
        )
    return counts_data, total_reads, lineage_lookup


def process_batch(
    accession_batch,
    taxid_cache,
    lumped_lineage_cache,
    tax_level,
    conn,
    counts_data,
    lineage_lookup,
):

    # Extract accessions only for DB lookups
    acc_only_batch = [item[0] for item in accession_batch]

    new_accessions = list(
        set([acc for acc in acc_only_batch if acc not in taxid_cache])
    )
    if new_accessions:
        taxid_map = get_taxids_for_accessions(new_accessions, conn)
        taxid_cache.update(taxid_map)

    taxids_to_lump = list(
        set([taxid_cache.get(acc, "Unknown") for acc in acc_only_batch])
    )
    taxids_to_lump = [tax_id for tax_id in taxids_to_lump if tax_id != "Unknown"]

    new_taxids_to_lump = [
        tax_id for tax_id in taxids_to_lump if tax_id not in lumped_lineage_cache
    ]
    if new_taxids_to_lump:
        lumped_map = tax_lump_batch_modified(new_taxids_to_lump, tax_level, conn)
        lumped_lineage_cache.update(lumped_map)

    # Loop through the batch, unpacking the new tags
    for accession, ds_score, nm_score, as_score, xm_score in accession_batch:
        taxid = taxid_cache.get(accession, "Unknown")
        lineage_result = lumped_lineage_cache.get(
            taxid, {"lineage": {}, "target_tax_id": "Unknown"}
        )
        target_taxid = lineage_result["target_tax_id"]

        # Initialize the data structure for the target tax ID
        if target_taxid not in counts_data:
            buckets = {}
            for x in BUCKET_LIST:
                buckets[x] = 0
            counts_data[target_taxid] = {
                "count": 0,
                "ds_scores": [],
                "nm_scores": [],
                "as_scores": [],
                "xm_scores": [],
                "buckets": buckets,
            }

        counts_data[target_taxid]["count"] += 1

        # Track the values if they exist
        if ds_score is not None:
            counts_data[target_taxid]["ds_scores"].append(ds_score)
            for x in BUCKET_LIST:
                if ds_score < float(x) and ds_score >= (float(x) - 0.1):
                    counts_data[target_taxid]["buckets"][x] += 1

        if nm_score is not None:
            counts_data[target_taxid]["nm_scores"].append(nm_score)

        if as_score is not None:
            counts_data[target_taxid]["as_scores"].append(as_score)

        if xm_score is not None:
            counts_data[target_taxid]["xm_scores"].append(xm_score)

        if target_taxid not in ["Unknown", "Other"]:
            lineage_lookup[target_taxid] = lineage_result["lineage"]
        elif target_taxid == "Unknown" and target_taxid not in lineage_lookup:
            lineage_lookup["Unknown"] = {rank: "Unknown" for rank in MAJOR_RANKS}
        elif target_taxid == "Other" and target_taxid not in lineage_lookup:
            lineage_lookup["Other"] = {rank: "Other" for rank in MAJOR_RANKS}
