from __future__ import annotations

from market_api.importer.mappings import SheetSpec


def quote_identifier(identifier: str) -> str:
    return '"' + identifier.replace('"', '""') + '"'


def qualify_table(schema: str, table: str) -> str:
    return f"{quote_identifier(schema)}.{quote_identifier(table)}"


def column_sql_type(kind: str) -> str:
    match kind:
        case "integer":
            return "integer"
        case "numeric":
            return "numeric"
        case "timestamp":
            return "timestamp"
        case _:
            return "text"


def record_column_names(spec: SheetSpec) -> list[str]:
    return ["源行号", *[column.db_name for column in spec.columns]]


def build_create_schema_sql(schema: str) -> str:
    return f"CREATE SCHEMA IF NOT EXISTS {quote_identifier(schema)}"


def build_drop_table_sql(schema: str, spec: SheetSpec) -> str:
    return f"DROP TABLE IF EXISTS {qualify_table(schema, spec.table_name)}"


def build_create_table_sql(schema: str, spec: SheetSpec) -> str:
    columns = ['  "源行号" integer NOT NULL']
    for column in spec.columns:
        columns.append(
            f"  {quote_identifier(column.db_name)} {column_sql_type(column.kind)}"
        )
    column_block = ",\n".join(columns)
    return f"CREATE TABLE {qualify_table(schema, spec.table_name)} (\n{column_block}\n)"


def build_copy_sql(schema: str, spec: SheetSpec) -> str:
    columns = ", ".join(quote_identifier(name) for name in record_column_names(spec))
    return f"COPY {qualify_table(schema, spec.table_name)} ({columns}) FROM STDIN"

