"""Local schemas and records for behavioral SQL tests; no cloud connections."""

from __future__ import annotations

import re
from datetime import UTC, date, datetime
from decimal import Decimal
from pathlib import Path
from uuid import UUID

from sqlalchemy import (
    Column,
    Date,
    DateTime,
    Integer,
    MetaData,
    Numeric,
    String,
    Table,
    UniqueConstraint,
    create_engine,
    select,
    text,
)
from sqlalchemy.schema import SchemaItem

from finops_batches.domain.models import BatchExecutionContext, Record

DAY = date(2026, 8, 1)
NOW = datetime(2026, 8, 2, tzinfo=UTC).replace(tzinfo=None)


def find_ddl_file(filename: str, *, anchor: Path | None = None) -> Path:
    """Find a project DDL independently of test depth and working directory."""
    location = Path(__file__) if anchor is None else anchor
    for root in location.resolve().parents:
        if (root / "src" / "finops_batches").is_dir() and (root / "ddl").is_dir():
            target = root / "ddl" / filename
            if not target.is_file():
                raise FileNotFoundError(f"DDL absent du dépôt identifié : {target}")
            return target
    raise FileNotFoundError(
        f"Racine du dépôt introuvable depuis {location}: "
        "dossiers src/finops_batches et ddl attendus."
    )


def context(day: date = DAY) -> BatchExecutionContext:
    """Create a complete, deterministic execution context."""
    return BatchExecutionContext(
        "MANUAL", day, 1, UUID("11111111-2222-3333-4444-555555555555")
    )


class Store:
    """Run portable SQL logic against SQLite with source DDL column constraints.

    MySQL index/storage/collation/JSON details are not emulated. Only columns,
    primary keys, natural unique keys and SQL defaults are translated.
    """

    def __init__(self, path: Path) -> None:
        self.url = f"sqlite:///{path}"
        self.engine = create_engine(self.url)
        self.metadata = MetaData()

    def ddl(self, filename: str) -> Table:
        """Translate one project's CREATE TABLE without executing its DROP statements."""
        sql = re.sub(r"--[^\n]*", "", find_ddl_file(filename).read_text())
        match = re.search(
            r"CREATE TABLE\s+(?:IF NOT EXISTS\s+)?`?(\w+)`?\s*\(", sql, re.IGNORECASE
        )
        assert match is not None
        depth = 1
        start = match.end()
        chunks: list[str] = []
        quoted = False
        for pos in range(start, len(sql)):
            char = sql[pos]
            if char == "'":
                quoted = not quoted
            if quoted:
                continue
            if char == "(":
                depth += 1
            elif char == ")":
                depth -= 1
            if depth == 0 or char == "," and depth == 1:
                chunks.append(sql[start:pos].strip())
                start = pos + 1
                if depth == 0:
                    break
        primary = re.search(r"PRIMARY KEY\s*\(([^)]+)\)", sql, re.IGNORECASE)
        primary_names: set[str] = (
            set(re.findall(r"\w+", primary.group(1))) if primary else set()
        )
        items: list[SchemaItem] = []
        for chunk in chunks:
            col = re.match(
                r"`?(\w+)`?\s+(BIGINT|TINYINT|INT|INTEGER|DECIMAL|DATETIME|DATE|BOOLEAN|VARCHAR|CHAR|LONGTEXT|TEXT|ENUM)\b",
                chunk,
                re.IGNORECASE,
            )
            if col is None:
                continue
            name, kind = col.group(1), col.group(2).upper()
            pk = name in primary_names
            nullable = "NOT NULL" not in chunk.upper() and not pk
            default_match = re.search(
                r"DEFAULT\s+('(?:[^']*)'|[-\d.]+|CURRENT_TIMESTAMP(?:\(\))?)",
                chunk,
                re.IGNORECASE,
            )
            default = (
                text(default_match.group(1).replace("()", ""))
                if default_match
                else None
            )
            if kind in {"BIGINT", "TINYINT", "INT", "INTEGER", "BOOLEAN"}:
                column = Column(
                    name,
                    Integer,
                    primary_key=pk,
                    nullable=nullable,
                    server_default=default,
                )
                items.append(column)
            elif kind == "DECIMAL":
                items.append(
                    Column(
                        name,
                        Numeric(38, 12),
                        primary_key=pk,
                        nullable=nullable,
                        server_default=default,
                    )
                )
            elif kind == "DATETIME":
                items.append(
                    Column(
                        name,
                        DateTime,
                        primary_key=pk,
                        nullable=nullable,
                        server_default=default,
                    )
                )
            elif kind == "DATE":
                items.append(
                    Column(
                        name,
                        Date,
                        primary_key=pk,
                        nullable=nullable,
                        server_default=default,
                    )
                )
            else:
                items.append(
                    Column(
                        name,
                        String,
                        primary_key=pk,
                        nullable=nullable,
                        server_default=default,
                    )
                )
        for chunk in chunks:
            if re.match(
                r"(?:UNIQUE KEY|CONSTRAINT \w+\s+UNIQUE)", chunk, re.IGNORECASE
            ):
                columns = re.search(r"\(([^)]+)\)", chunk)
                assert columns is not None
                items.append(UniqueConstraint(*re.findall(r"\w+", columns.group(1))))
        table = Table(match.group(1), self.metadata, *items)
        table.create(self.engine)
        return table

    def insert(self, table: Table, **overrides: object) -> Record:
        """Fill required fields, leaving explicit test values in control."""
        row: Record = {}
        for column in table.c:
            if column.primary_key and isinstance(column.type, Integer):
                continue
            if column.nullable or column.server_default is not None:
                continue
            if isinstance(column.type, Numeric):
                row[column.name] = Decimal(1)
            elif isinstance(column.type, Integer):
                row[column.name] = 1
            elif isinstance(column.type, DateTime):
                row[column.name] = NOW
            elif isinstance(column.type, Date):
                row[column.name] = DAY
            else:
                row[column.name] = column.name
        row.update(overrides)
        with self.engine.begin() as conn:
            conn.execute(table.insert(), row)
        return row

    def rows(self, table: Table) -> list[Record]:
        """Read the persisted state for assertions independent of loader return counts."""
        with self.engine.connect() as conn:
            return [dict(row) for row in conn.execute(select(table)).mappings()]

    def close(self) -> None:
        """Release the local database."""
        self.engine.dispose()
