"""Aplica schema.sql no SQL Server local, separando pelos GO (o pyodbc nao entende GO)."""
import sys
import pyodbc

CAMINHO = r"D:\RoshEmulator\server\schema.sql"
CONEXAO = ("DRIVER={ODBC Driver 18 for SQL Server};SERVER=localhost;"
           "DATABASE=master;Trusted_Connection=yes;TrustServerCertificate=yes")


def lotes(sql: str):
    atual = []
    for linha in sql.splitlines():
        if linha.strip().upper() == "GO":
            if atual:
                yield "\n".join(atual)
            atual = []
        else:
            atual.append(linha)
    if atual and "\n".join(atual).strip():
        yield "\n".join(atual)


def main() -> int:
    sql = open(CAMINHO, encoding="utf-8").read()
    con = pyodbc.connect(CONEXAO, timeout=10, autocommit=True)
    cur = con.cursor()
    for i, lote in enumerate(lotes(sql), 1):
        if not lote.strip():
            continue
        primeira = next((l for l in lote.splitlines() if l.strip() and not l.strip().startswith("--")), "")
        try:
            cur.execute(lote)
            print(f"  lote {i}: ok   {primeira.strip()[:70]}")
        except Exception as e:
            print(f"  lote {i}: FALHOU  {primeira.strip()[:70]}")
            print(f"      {str(e)[:250]}")
            return 1
    con.close()
    print("schema aplicado")
    return 0


if __name__ == "__main__":
    sys.exit(main())
