from __future__ import annotations

import glob
import json
import os
import random
import signal
import time
from concurrent.futures import as_completed
from concurrent.futures import ProcessPoolExecutor
from datetime import datetime

import backoff
import psutil
import requests
import typesense
from tqdm import tqdm

MASTER_API_KEY = os.environ.get("MASTER_API_KEY")
TYPESENSE_HOST = "cartonsearch.singularbyte.tech"
TYPESENSE_PORT = "443"
# TYPESENSE_HOST = "54.37.30.114"
# TYPESENSE_PORT = "8108"

BATCH_SIZE = 1
MAX_WORKERS = 1

if not MASTER_API_KEY:
    print("Please set the MASTER_API_KEY environment variable.")
    exit(1)


# Mapping of characters to numeric codes
codes = {
    "B": 1,
    "P": 1,
    "C": 2,
    "Ç": 2,
    "K": 2,
    "Q": 2,
    "D": 3,
    "T": 3,
    "L": 4,
    "M": 5,
    "N": 5,
    "R": 6,
    "G": 7,
    "J": 7,
    "X": 8,
    "Z": 8,
    "S": 8,
    "F": 9,
    "V": 9,
    "A": 0,
    "À": 0,
    "Â": 0,
    "Ä": 0,
    "E": 0,
    "É": 0,
    "È": 0,
    "Ê": 0,
    "Ë": 0,
    "I": 0,
    "Î": 0,
    "Ï": 0,
    "O": 0,
    "Ô": 0,
    "Ö": 0,
    "U": 0,
    "Û": 0,
    "Ü": 0,
    "Ù": 0,
}


def soundex(string, length=4):
    # Capitalize and normalize the string
    buffer = string.upper().encode("ascii", "ignore").decode("ascii")

    # Init result with the first letter
    result = buffer[0]
    previous = codes.get(result, None)

    # Map all chars
    for i in range(1, len(buffer)):
        letter = buffer[i]
        code = codes.get(letter)

        # Ignore letter if not in mapping
        if code is None:
            continue

        # Append code if different than previous
        if code is not None and code != previous:
            result += str(code)

            # Check if Soundex key is fulfilled
            if len(result) == length:
                return result

        # Save previous for next loop
        previous = code

    # Fill with '0' to reach desired length
    return result.ljust(length, "0")


def terminate_children(signum, frame):
    """
    Terminate all child processes spawned by this process.
    """
    current_process = psutil.Process()
    children = current_process.children(recursive=True)
    for child in children:
        child.terminate()
    current_process.terminate()


signal.signal(signal.SIGINT, terminate_children)


def create_api_key(client):
    new_key = {"description": "New API Key", "actions": ["*"], "collections": ["*"]}

    response = client.keys.create(new_key)
    print("API Key created:", json.dumps(response, indent=2))


def list_api_keys(client):
    response = client.keys.retrieve()
    print("API Keys:", json.dumps(response, indent=2))


def list_collections(client):
    response = client.collections.retrieve()
    print("Collections:", json.dumps(response, indent=2))


def create_companiesfr_collection(client, collection_name: str = "companiesfr"):
    schema = {
        "name": collection_name,
        "enable_nested_fields": True,
        "fields": [
            {"name": "siren", "type": "string"},
            {"name": "legal_name", "locale": "fr", "type": "string"},
            {"name": "legal_name_phonetic", "locale": "fr", "type": "string"},
            {"name": "entity_type", "type": "string", "facet": True},
        ],
    }

    client.collections.create(schema)
    print("Collection created:", json.dumps(schema, indent=2))


def save_current_batch(batch_number):
    """Save the current batch number to a file."""
    with open("cursor_batch.txt", "w") as f:
        f.write(str(batch_number))


def get_starting_batch():
    """Read the last processed batch number from the file."""
    if os.path.exists("cursor_batch.txt"):
        with open("cursor_batch.txt", "r") as f:
            return int(f.read().strip())
    return 0


@backoff.on_exception(
    backoff.expo,
    (requests.exceptions.RequestException, typesense.exceptions.TypesenseClientError),
    max_tries=5,
)
def process_file_batch(file_paths, client, collection_name):
    documents = []
    for filename in file_paths:
        with open(filename, "r") as file:
            for line in file:
                document = json.loads(line)
                # convert any None to empty string
                for key, value in document.items():
                    if value is None:
                        document[key] = ""

                # add phonetic name
                document["legal_name_phonetic"] = (
                    soundex(document["legal_name"]) if document["legal_name"] else ""
                )
                documents.append(document)
    if not documents:
        return 0

    # Index documents to Typesense
    responses = client.collections[collection_name].documents.import_(
        documents, {"action": "upsert", "dirty_values": "drop"}
    )

    for response in responses:
        if not response["success"]:
            print("Error importing documents:", response)

    return len(documents)


def index_documents(client):
    # Generate a unique alias name
    base_name = "companiesfr"
    rand = random.randint(10000, 99999)
    day_month_year = datetime.now().strftime("%d%m%Y")
    collection_name = f"{base_name}_alias_{day_month_year}_{rand}"
    # create collection
    create_companiesfr_collection(client, collection_name)

    file_iterator = glob.glob("export_data/*.jsonl", recursive=True)
    print(f"Indexing from {len(file_iterator)} batches...")

    # do batch of 10 files
    file_batches = [
        file_iterator[i : i + BATCH_SIZE] for i in range(0, len(file_iterator), BATCH_SIZE)
    ]

    start_batch = get_starting_batch()
    file_batches = file_batches[start_batch:]

    progress_bar = tqdm(
        total=len(file_iterator) - start_batch * BATCH_SIZE, desc="Processing SIRENs"
    )
    with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
        try:
            for i, batch in enumerate(file_batches):
                future = executor.submit(process_file_batch, batch, client, collection_name)
                # get results
                result_count = future.result()
                progress_bar.update(result_count)
                save_current_batch(start_batch + i)
        except KeyboardInterrupt:
            pass  # Handle Ctrl+C here if needed
        finally:
            executor.shutdown(wait=False)

    aliased_collection = {"collection_name": collection_name}
    #  client.aliases.upsert('companiesfr', aliased_collection)
    print(f"Documents indexed on new collection '{collection_name}'.")
    # print(f"Documents indexed and alias <companiesfr> updated to new collection '{collection_name}'.")


def update_alias(client):
    # list all aliases
    alias_name = "companiesfr"
    try:
        alias = client.aliases[alias_name].retrieve()
    except typesense.exceptions.ObjectNotFound:
        alias = None

    current_collection = None
    if alias:
        current_collection = alias["collection_name"]

    list_collections = client.collections.retrieve()
    collection_names = [c["name"] for c in list_collections]

    collection_to_delete = None
    if current_collection in collection_names:
        collection_to_delete = current_collection

    print("Collections:", json.dumps(list_collections, indent=2))
    input_collection = input("Enter collection to link to alias `companiesfr`: ")
    aliased_collection = {"collection_name": input_collection}

    client.aliases.upsert("companiesfr", aliased_collection)
    print(f"Alias <companiesfr> updated to new collection '{input_collection}'.")

    # delete old collection
    if collection_to_delete:
        print(f"Deleting old collection '{collection_to_delete}'...")
        client.collections[collection_to_delete].delete()
        print(f"Collection '{collection_to_delete}' deleted.")


def main_menu(client):
    while True:
        print("\nTypesense Management")
        print("1. Create API Key")
        print("2. List API Keys")
        print("3. Create companiesfr collection")
        print("4. List collection")
        print("5. Index companiesfr")
        print("6. Update alias on companiesfr")
        print("7. Exit")
        choice = input("Enter your choice: ")

        if choice == "1":
            create_api_key(client)
            break
        if choice == "2":
            list_api_keys(client)
            break
        if choice == "3":
            create_companiesfr_collection(client)
            break
        if choice == "4":
            list_collections(client)
            break
        if choice == "5":
            index_documents(client)
            break
        if choice == "6":
            update_alias(client)
            break
        elif choice == "7":
            print("Exiting...")
            break
        else:
            print("Invalid choice, please try again.")


if __name__ == "__main__":
    client = typesense.Client(
        {
            "nodes": [
                {
                    "host": TYPESENSE_HOST,
                    "port": TYPESENSE_PORT,
                    "protocol": "https" if TYPESENSE_PORT == "443" else "http",
                }
            ],
            "api_key": MASTER_API_KEY.strip(),
            "connection_timeout_seconds": 10,
        }
    )

    while not client.operations.is_healthy():
        print("cluster is unhealthy, retrying...")
        time.sleep(1)
    print("cluster is healthy")

    main_menu(client)
