from __future__ import annotations

import re
from datetime import date

from sqlalchemy import create_engine, text
from sqlalchemy.engine import Connection, Engine

_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_MONTH_PARTITION_RE = re.compile(r"^p(\d{4})(\d{2})$")


class MariaDbMonthlyPartitionManager:
    """
    Ensure that a monthly RANGE partition exists for a MariaDB table.

    Expected naming convention:

        p202611 -> VALUES LESS THAN ('2026-12-01')
        p202612 -> VALUES LESS THAN ('2027-01-01')
        p202701 -> VALUES LESS THAN ('2027-02-01')

    The manager supports tables:
    - ending on a bounded monthly partition;
    - ending with a pmax / MAXVALUE partition.
    """

    def __init__(
        self,
        *,
        database_url: str,
        table_name: str,
        lock_timeout_seconds: int = 30,
    ) -> None:
        self._validate_identifier(
            table_name,
            "table_name",
        )

        self._engine: Engine = create_engine(
            database_url,
            pool_pre_ping=True,
        )

        self._table_name = table_name
        self._lock_timeout_seconds = lock_timeout_seconds

    def ensure_for_date(
        self,
        business_date: date,
    ) -> None:
        target_month = date(
            business_date.year,
            business_date.month,
            1,
        )

        with self._engine.connect() as connection:
            self._validate_database(connection)

            lock_name = f"partition:{self._table_name}"

            lock_result = connection.execute(
                text(
                    """
                    SELECT GET_LOCK(
                        :lock_name,
                        :timeout_seconds
                    )
                    """
                ),
                {
                    "lock_name": lock_name,
                    "timeout_seconds": (self._lock_timeout_seconds),
                },
            ).scalar_one()

            if lock_result != 1:
                raise TimeoutError(
                    "Impossible d'obtenir le verrou "
                    "de gestion des partitions pour "
                    f"{self._table_name!r}."
                )

            try:
                self._ensure_months(
                    connection,
                    target_month,
                )
            finally:
                connection.execute(
                    text(
                        """
                        SELECT RELEASE_LOCK(:lock_name)
                        """
                    ),
                    {
                        "lock_name": lock_name,
                    },
                )

    def _ensure_months(
        self,
        connection: Connection,
        target_month: date,
    ) -> None:
        partition_names = self._partition_names(connection)

        target_partition = self._partition_name(target_month)

        if target_partition in partition_names:
            return

        existing_months = sorted(
            month
            for partition_name in partition_names
            if (month := self._month_from_partition_name(partition_name)) is not None
        )

        if not existing_months:
            raise ValueError(
                f"Aucune partition mensuelle trouvée sur {self._table_name!r}."
            )

        latest_month = existing_months[-1]

        if target_month < latest_month:
            raise ValueError(
                "Une partition historique intermédiaire "
                "est absente. La création automatique "
                "ne gère que l'extension en fin de plage. "
                f"Table={self._table_name!r}, "
                f"partition={target_partition!r}."
            )

        month = self._next_month(latest_month)

        has_max_partition = "pmax" in partition_names

        while month <= target_month:
            partition_name = self._partition_name(month)

            if partition_name not in partition_names:
                self._create_partition(
                    connection,
                    month,
                    has_max_partition=(has_max_partition),
                )

                partition_names.add(partition_name)

            month = self._next_month(month)

    def _create_partition(
        self,
        connection: Connection,
        month: date,
        *,
        has_max_partition: bool,
    ) -> None:
        partition_name = self._partition_name(month)

        upper_bound = self._next_month(month).isoformat()

        table_name = self._quoted_identifier(self._table_name)

        if has_max_partition:
            statement = f"""
                ALTER TABLE {table_name}
                REORGANIZE PARTITION pmax INTO
                (
                    PARTITION {partition_name}
                        VALUES LESS THAN (
                            '{upper_bound}'
                        ),
                    PARTITION pmax
                        VALUES LESS THAN (
                            MAXVALUE
                        )
                )
            """
        else:
            statement = f"""
                ALTER TABLE {table_name}
                ADD PARTITION
                (
                    PARTITION {partition_name}
                        VALUES LESS THAN (
                            '{upper_bound}'
                        )
                )
            """

        connection.exec_driver_sql(statement)

    def _partition_names(
        self,
        connection: Connection,
    ) -> set[str]:
        result = connection.execute(
            text(
                """
                SELECT
                    PARTITION_NAME
                FROM information_schema.PARTITIONS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = :table_name
                  AND PARTITION_NAME IS NOT NULL
                ORDER BY PARTITION_ORDINAL_POSITION
                """
            ),
            {
                "table_name": self._table_name,
            },
        )

        names: set[str] = set()

        for row in result:
            value = row[0]

            if isinstance(value, str):
                names.add(value)

        if not names:
            raise RuntimeError(f"La table {self._table_name!r} n'est pas partitionnée.")

        return names

    @staticmethod
    def _partition_name(
        month: date,
    ) -> str:
        return f"p{month.year:04d}{month.month:02d}"

    @staticmethod
    def _month_from_partition_name(
        partition_name: str,
    ) -> date | None:
        match = _MONTH_PARTITION_RE.fullmatch(partition_name)

        if match is None:
            return None

        year = int(match.group(1))
        month = int(match.group(2))

        if not 1 <= month <= 12:
            return None

        return date(
            year,
            month,
            1,
        )

    @staticmethod
    def _next_month(
        value: date,
    ) -> date:
        if value.month == 12:
            return date(
                value.year + 1,
                1,
                1,
            )

        return date(
            value.year,
            value.month + 1,
            1,
        )

    @staticmethod
    def _validate_identifier(
        value: str,
        field_name: str,
    ) -> None:
        if _IDENTIFIER_RE.fullmatch(value) is None:
            raise ValueError(f"{field_name} SQL invalide: {value!r}.")

    @staticmethod
    def _quoted_identifier(
        value: str,
    ) -> str:
        return f"`{value}`"

    @staticmethod
    def _validate_database(
        connection: Connection,
    ) -> None:
        dialect_name = connection.engine.dialect.name

        if dialect_name not in {
            "mysql",
            "mariadb",
        }:
            raise ValueError(
                "MariaDbMonthlyPartitionManager "
                "ne peut être utilisé qu'avec "
                "MariaDB/MySQL."
            )

    def close(self) -> None:
        self._engine.dispose()
