import textwrap
from typing import Callable


class ExternalDataTempTableBuilder:

    def __init__(self):
        self._table_name = None
        self._fields: dict[str, str] = {}
        self._primary_key = "id"
        self._join_ref_table = None
        self._value_getter = None

    @property
    def table_name(self) -> str:
        return self._table_name

    @property
    def fields(self) -> dict[str, str]:
        return self._fields

    @property
    def primary_key(self) -> str:
        return self._primary_key

    @property
    def join_ref_table(self) -> str:
        return self._join_ref_table

    def with_table_name(self, table_name: str) -> "ExternalDataTempTableBuilder":
        self._join_ref_table = table_name

        if "." in table_name:
            table_name = table_name.split(".")[-1]

        if not table_name.endswith("_temp"):
            table_name = f"{table_name}_temp"

        self._table_name = table_name
        return self

    def with_field(
        self, name: str, sql_type: str, primary=False
    ) -> "ExternalDataTempTableBuilder":
        if primary:
            sql_type += " PRIMARY KEY"
            self._primary_key = name
        self._fields[name] = sql_type
        return self

    def with_value_getter(
        self, value_getter: Callable
    ) -> "ExternalDataTempTableBuilder":
        self._value_getter = value_getter
        return self

    async def build(self) -> str:
        assert self._table_name is not None, "Table name is required"
        assert self._value_getter is not None, "Value getter is required"

        values_str = ", ".join([f"{value}" for value in await self._value_getter()])

        return textwrap.dedent(
            f"""
            DROP TABLE IF EXISTS {self._table_name};
            CREATE TEMP TABLE {self._table_name} (
                {", ".join([f"{k} {v}" for k, v in self._fields.items()])}
            );
            
            INSERT INTO {self._table_name} VALUES {values_str};
        """
        )
