from __future__ import annotations

from pyspark.sql import SparkSession


def _q(identifier: str) -> str:
    return f"`{identifier.replace('`', '``')}`"


def create_catalog_sql(catalog: str) -> str:
    return f"CREATE CATALOG IF NOT EXISTS {_q(catalog)}"


def create_schema_sql(catalog: str, schema: str) -> str:
    return f"CREATE SCHEMA IF NOT EXISTS {_q(catalog)}.{_q(schema)}"


def register_external_delta_table_sql(catalog: str, schema: str, table: str, location: str) -> str:
    fq = f"{_q(catalog)}.{_q(schema)}.{_q(table)}"
    return f"CREATE TABLE IF NOT EXISTS {fq} USING DELTA LOCATION '{location}'"


def create_catalog(spark: SparkSession, catalog: str) -> None:
    spark.sql(create_catalog_sql(catalog))


def create_schema(spark: SparkSession, catalog: str, schema: str) -> None:
    create_catalog(spark, catalog)
    spark.sql(create_schema_sql(catalog, schema))


def register_external_delta_table(
    spark: SparkSession, *, catalog: str, schema: str, table: str, location: str
) -> None:
    spark.sql(register_external_delta_table_sql(catalog, schema, table, location))
