#!/usr/bin/env python3
"""
Initialize poweron_automation2 database for the Automation2 feature.

Creates the poweron_automation2 database if it does not exist.
Uses DB_* config. Tables (Automation2Workflow, Automation2WorkflowRun,
Automation2HumanTask) are auto-created by the connector on first use.

Usage:
    python scripts/script_db_init_automation2.py [--dry-run]
"""

import os
import sys
import argparse
import logging
from pathlib import Path

scriptPath = Path(__file__).resolve()
gatewayPath = scriptPath.parent.parent
sys.path.insert(0, str(gatewayPath))
os.chdir(str(gatewayPath))

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)

import psycopg2
from modules.shared.configuration import APP_CONFIG

DB_NAME = "poweron_automation2"


def _get_config():
    """Get DB config from APP_CONFIG."""
    host = APP_CONFIG.get("DB_HOST", "localhost")
    port = int(APP_CONFIG.get("DB_PORT", "5432"))
    user = APP_CONFIG.get("DB_USER")
    password = (
        APP_CONFIG.get("DB_PASSWORD_SECRET") or APP_CONFIG.get("DB_PASSWORD")
    )
    return {"host": host, "port": port, "user": user, "password": password}


def init_automation2_db(dry_run: bool = False) -> bool:
    """Create poweron_automation2 database if it does not exist."""
    config = _get_config()
    if not config["user"] or not config["password"]:
        logger.error("DB_USER and DB_PASSWORD required")
        return False

    try:
        conn = psycopg2.connect(
            host=config["host"],
            port=config["port"],
            database="postgres",
            user=config["user"],
            password=config["password"],
        )
        conn.autocommit = True

        with conn.cursor() as cur:
            cur.execute(
                "SELECT 1 FROM pg_database WHERE datname = %s",
                (DB_NAME,),
            )
            exists = cur.fetchone() is not None

            if exists:
                logger.info("Database %s already exists", DB_NAME)
            else:
                if dry_run:
                    logger.info("[DRY-RUN] Would create database %s", DB_NAME)
                else:
                    cur.execute(f'CREATE DATABASE "{DB_NAME}"')
                    logger.info("Created database %s", DB_NAME)

        conn.close()
        return True
    except Exception as e:
        logger.error("Failed to init %s: %s", DB_NAME, e)
        return False


def main():
    parser = argparse.ArgumentParser(description="Initialize poweron_automation2 database")
    parser.add_argument("--dry-run", action="store_true", help="Do not create, only report")
    args = parser.parse_args()
    ok = init_automation2_db(dry_run=args.dry_run)
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
