#!/usr/bin/env python3
import os
import sys
from pathlib import Path

try:
    import pymysql
except ImportError:
    print('pymysql가 필요합니다. pip install pymysql 후 다시 실행해주세요.', file=sys.stderr)
    sys.exit(1)

ROOT = Path(__file__).resolve().parents[1]
ENV_PATH = ROOT / '.env'


def load_env(path: Path):
    if not path.exists():
        return
    for raw in path.read_text().splitlines():
        line = raw.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(ENV_PATH)

required = ['DB_HOST', 'DB_USER', 'DB_PASSWORD', 'DB_NAME']
missing = [k for k in required if not os.environ.get(k)]
if missing:
    print(f'필수 DB 환경변수가 없습니다: {", ".join(missing)}', file=sys.stderr)
    sys.exit(1)

conn = pymysql.connect(
    host=os.environ['DB_HOST'],
    user=os.environ['DB_USER'],
    password=os.environ['DB_PASSWORD'],
    database=os.environ['DB_NAME'],
    port=int(os.environ.get('DB_PORT', '3306')),
    charset='utf8mb4',
    autocommit=False,
)

GHOST_RUNNING_PRIVACY_KO = """
<h1>고스트러닝 개인정보 처리방침</h1>
<div class="highlight"><strong>시행일자:</strong> 2026년 04월 10일<br><strong>최종 수정일:</strong> 2026년 04월 10일</div>
<p>고스트러닝은 러닝 기록 제공, 앱 품질 개선, 광고 설정 운영을 위해 필요한 최소한의 정보를 처리합니다.</p>
""".strip()

GHOST_RUNNING_PRIVACY_EN = """
<h1>Ghost Running Privacy Policy</h1>
<div class="highlight"><strong>Effective Date:</strong> April 10, 2026<br><strong>Last Updated:</strong> April 10, 2026</div>
<p>Ghost Running processes the minimum information required to operate running records, improve service quality, and apply ad settings.</p>
""".strip()

with conn.cursor() as cur:
    cur.execute(
        """
        CREATE TABLE IF NOT EXISTS ghost_running_ad_settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            ad_mode ENUM('test', 'release') DEFAULT 'test',
            ios_banner_ad_id VARCHAR(255),
            ios_interstitial_ad_id VARCHAR(255),
            android_banner_ad_id VARCHAR(255),
            android_interstitial_ad_id VARCHAR(255),
            test_ios_banner_ad_id VARCHAR(255),
            test_ios_interstitial_ad_id VARCHAR(255),
            test_android_banner_ad_id VARCHAR(255),
            test_android_interstitial_ad_id VARCHAR(255),
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """
    )
    cur.execute('SELECT id FROM ghost_running_ad_settings LIMIT 1')
    if not cur.fetchone():
        cur.execute(
            """
            INSERT INTO ghost_running_ad_settings (
                ad_mode, ios_banner_ad_id, ios_interstitial_ad_id, android_banner_ad_id, android_interstitial_ad_id,
                test_ios_banner_ad_id, test_ios_interstitial_ad_id, test_android_banner_ad_id, test_android_interstitial_ad_id
            ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
            """,
            ('test', '', '', '', '',
             'ca-app-pub-3940256099942544/2934735716', 'ca-app-pub-3940256099942544/4411468910',
             'ca-app-pub-3940256099942544/6300978111', 'ca-app-pub-3940256099942544/1033173712')
        )

    policy_rows = [
        ('ghost-running', 'privacy', 'ko', '고스트러닝 개인정보 처리방침', GHOST_RUNNING_PRIVACY_KO, '1.0', '2026-04-10'),
        ('ghost-running', 'privacy', 'en', 'Ghost Running Privacy Policy', GHOST_RUNNING_PRIVACY_EN, '1.0', '2026-04-10'),
    ]
    for row in policy_rows:
        cur.execute(
            """
            INSERT INTO app_policies (app_name, policy_type, language_code, title, content, version, effective_date)
            VALUES (%s, %s, %s, %s, %s, %s, %s)
            ON DUPLICATE KEY UPDATE
                title = VALUES(title),
                content = VALUES(content),
                version = VALUES(version),
                effective_date = VALUES(effective_date)
            """,
            row,
        )

conn.commit()
conn.close()
print('ghost-running DB seed/setup 완료')
