"""Add must_change_password flag for one-time temp password logins."""
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from sqlalchemy import text
from app.core.database import engine


def run():
    dialect = engine.dialect.name
    if dialect == "sqlite":
        stmts = [
            "ALTER TABLE users ADD COLUMN must_change_password BOOLEAN DEFAULT 0",
        ]
    else:
        stmts = [
            """
            ALTER TABLE users
            ADD COLUMN IF NOT EXISTS must_change_password BOOLEAN NOT NULL DEFAULT FALSE
            """,
        ]
    with engine.begin() as conn:
        for stmt in stmts:
            try:
                conn.execute(text(stmt))
            except Exception as exc:
                if "duplicate column" in str(exc).lower() or "already exists" in str(exc).lower():
                    continue
                raise
    print("must_change_password column ready on users")


if __name__ == "__main__":
    run()
