import os
from pathlib import Path

import mysql.connector


def load_env_file():
    env_path = Path(__file__).resolve().parent.parent / '.env'
    if not env_path.exists():
        return

    for raw_line in env_path.read_text(encoding='utf-8').splitlines():
        line = raw_line.strip()
        if not line or line.startswith('#') or '=' not in line:
            continue
        key, value = line.split('=', 1)
        os.environ.setdefault(key.strip(), value.strip())


def add_page_plan_column(cursor, table_name):
    try:
        cursor.execute(
            f'ALTER TABLE {table_name} '
            'ADD COLUMN page_plan LONGTEXT DEFAULT NULL AFTER selected_diary_ids'
        )
        print(f'OK: add {table_name}.page_plan')
    except mysql.connector.Error as error:
        if error.errno == 1060:
            print(f'SKIP: {table_name}.page_plan already exists')
            return
        raise


def run():
    load_env_file()
    connection = None
    cursor = None
    try:
        connection = mysql.connector.connect(
            host=os.environ.get('DB_HOST', 'officialsite.kr'),
            port=int(os.environ.get('DB_PORT', '23306')),
            user=os.environ.get('DB_USER', 'admin'),
            password=os.environ.get('DB_PASSWORD', ''),
            database=os.environ.get('DB_NAME', 'app_master'),
        )
        cursor = connection.cursor()
        add_page_plan_column(cursor, 'babynote_kidsnote_requests')
        add_page_plan_column(cursor, 'babynote_kidsnote_payment_orders')
        connection.commit()
        print('OK: BabyNote kidsnote page plan migration complete')
    finally:
        if cursor is not None:
            cursor.close()
        if connection is not None and connection.is_connected():
            connection.close()


if __name__ == '__main__':
    run()
