"""
One-command ingestion runner for QA & Plant Checksheets.
Reads and executes 'backend/migrations/003_ingest_all_qa_and_checklists.sql'
using the active SQLAlchemy / asyncpg database connection.
"""
import asyncio
import os
import sys

# Ensure UTF-8 output
if sys.platform == 'win32':
    sys.stdout.reconfigure(encoding='utf-8')

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from app.core.database import AsyncSessionLocal

SQL_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'migrations', '003_ingest_all_qa_and_checklists.sql'))

async def main():
    print(f"Reading SQL file: {SQL_FILE}")
    if not os.path.exists(SQL_FILE):
        print(f"Error: SQL file not found at {SQL_FILE}")
        return

    with open(SQL_FILE, 'r', encoding='utf-8') as f:
        sql_content = f.read()

    print(f"Executing SQL ingestion script ({len(sql_content):,} bytes)...")
    async with AsyncSessionLocal() as db:
        conn = await db.connection()
        raw_conn = await conn.get_raw_connection()
        await raw_conn.driver_connection.execute(sql_content)
        print("Done! QA and plant checksheets successfully ingested.")

if __name__ == '__main__':
    asyncio.run(main())
