from util.var import BATCH_SIZE, BUCKET_LIST, TAXONOMY_ORDER, MAJOR_RANKS

def get_taxids_for_accessions(accessions, conn):
    accession_map = {}
    if not accessions or not conn:
        return accession_map
    
    try:
        with conn.cursor() as cur:
            cur.execute("""
                SELECT accession_version, tax_id
                FROM accession_taxid
                WHERE accession_version = ANY(%s);
            """, (list(set(accessions)),))
            for row in cur.fetchall():
                accession_map[row[0]] = row[1]
    except Exception as e:
        print(f"[Error] Batch query failed: {e}")
    return accession_map

def get_lineage_from_taxid(taxid, target_tax_level, conn):
    full_lineage = {} 
    target_taxid = None

    if not conn:
        return target_taxid, {}

    current_taxid = taxid
    
    while True:
        if not current_taxid or current_taxid == 1:
            break
            
        try:
            with conn.cursor() as cur:
                cur.execute("""
                    SELECT tax_id, parent_tax_id, rank
                    FROM nodes
                    WHERE tax_id = %s;
                """, (current_taxid,))
                info = cur.fetchone()
        except Exception:
            break

        if not info:
            break
        tax_id, parent_tax_id, rank = info
        rank = rank.lower()
        if rank not in full_lineage:
            full_lineage[rank] = tax_id
        if rank == target_tax_level.lower():
            target_taxid = tax_id

        current_taxid = parent_tax_id
    
    final_lineage = {rank: full_lineage[rank] for rank in MAJOR_RANKS if rank in full_lineage}
    
    return (target_taxid, final_lineage) if target_taxid else ("Other", final_lineage)

def get_latin_names_batch(tax_ids, conn):
    name_map = {}
    if not tax_ids or not conn:
        return name_map

    numeric_tax_ids = [tid for tid in tax_ids if isinstance(tid, int) or (isinstance(tid, str) and tid.isdigit())]
    
    if not numeric_tax_ids:
        return name_map

    try:
        with conn.cursor() as cur:
            cur.execute("""
                SELECT tax_id, name_txt
                FROM scientific_names
                WHERE tax_id = ANY(%s);
            """, (numeric_tax_ids,))
            for row in cur.fetchall():
                name_map[row[0]] = row[1]
    except Exception as e:
        print(f"[Error] Batch name query failed: {e}")
        
    final_name_map = {}
    for tid in tax_ids:
        if tid in name_map:
            final_name_map[tid] = name_map[tid]
        elif str(tid).isdigit() and int(tid) in name_map:
            final_name_map[tid] = name_map[int(tid)]
        elif tid in ["Unknown", "Other"]:
            final_name_map[tid] = tid
        elif tid in numeric_tax_ids:
            final_name_map[tid] = f"TaxID:{tid}"
            
    return final_name_map