import os
import re
from typing import List, Optional

from alembic import op

revision = "0006"
down_revision = "0005"
branch_labels = None
depends_on = None

_DOLLAR_TAG_RE = re.compile(r"\$\w+\$")


def _find_dollar_tag(line: str) -> Optional[str]:
    m = _DOLLAR_TAG_RE.search(line.strip())
    return m.group(0) if m else None


def _split_statements(sql: str) -> List[str]:
    statements: List[str] = []
    current: List[str] = []
    in_dollar = False
    dollar_tag: Optional[str] = None

    for line in sql.split("\n"):
        stripped = line.strip()

        if not in_dollar:
            tag = _find_dollar_tag(stripped)
            if tag and tag.endswith("$") and tag.startswith("$"):
                dollar_tag = tag
                in_dollar = True
                current.append(line)
                continue

        if in_dollar and dollar_tag and stripped.startswith(dollar_tag):
            after = stripped[len(dollar_tag):].strip()
            if after == ";" or after == "":
                in_dollar = False
                dollar_tag = None
                if after == ";":
                    current.append(line)
                    statements.append("\n".join(current))
                    current = []
                    continue

        if not in_dollar and stripped.rstrip().endswith(";"):
            current.append(line)
            statements.append("\n".join(current))
            current = []
            continue

        current.append(line)

    remaining = "\n".join(current).strip()
    if remaining:
        statements.append(remaining)

    return statements


def upgrade() -> None:
    ddl_path = os.path.join(os.path.dirname(__file__), "sql", "0006_form3.sql")
    with open(ddl_path) as f:
        content = f.read()

    statements = _split_statements(content)
    for stmt in statements:
        stripped = stmt.strip().rstrip(";").strip()
        if not stripped:
            continue
        if all(l.strip().startswith("--") or not l.strip() for l in stripped.split("\n")):
            continue
        op.execute(stripped)


def downgrade() -> None:
    pass
