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().strip('"').strip("'"))


load_env_file()

DB_CONFIG = {
    "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"),
}

CREATE_VISIBLE_USERS_TABLE = """
CREATE TABLE IF NOT EXISTS babynote_calendar_visible_users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id VARCHAR(36) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uniq_user_id (user_id),
  INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
"""

INSERT_DEFAULT_SETTING = """
INSERT IGNORE INTO app_settings (
  app_name,
  setting_key,
  setting_value,
  setting_type,
  description
) VALUES (
  'babynote',
  'calendar_visible',
  'true',
  'boolean',
  '함께 챙기기 캘린더 전체 사용자 노출 여부'
)
"""


def run():
    connection = None
    cursor = None
    try:
        connection = mysql.connector.connect(**DB_CONFIG)
        cursor = connection.cursor()
        cursor.execute(CREATE_VISIBLE_USERS_TABLE)
        cursor.execute(INSERT_DEFAULT_SETTING)
        connection.commit()
        print("OK: babynote calendar visibility schema applied")
    finally:
        if cursor is not None:
            cursor.close()
        if connection is not None and connection.is_connected():
            connection.close()


if __name__ == "__main__":
    run()
