import pathlib
from typing import Dict


def table_files(sql_file: pathlib.Path) -> Dict[str, str]:
    """
    Associates the name of an output file to its SQL table, by reading the
    snb-load.sql script
    """
    results = {}
    with open(sql_file, "r", encoding="utf-8") as in_fd:
        for line in in_fd:
            line = line.strip()
            if not line.startswith("COPY"):
                # Ignore lines we don't care about
                continue

            # Find important indices
            table_start_idx = len("COPY ")
            table_end_idx = line.index(" FROM ", table_start_idx)
            csv_start_idx = line.index("'", table_end_idx + len("FROM"))
            csv_end_idx = line.index("'", csv_start_idx + 1)

            # Extract the table name
            table_name = line[table_start_idx:table_end_idx].strip()
            if "(" in table_name:
                # Got a set of columns with the table name
                table_name = table_name[: table_name.index("(")].strip()

            # Extract the name of the CSV file (full Docker path)
            csv_path = line[csv_start_idx + 1 : csv_end_idx]
            csv_name = csv_path.rsplit("/", 1)[-1]

            # Store it
            results[csv_name] = table_name

    return results