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


def load_env(env_path: Path) -> dict:
    data = {}
    if not env_path.exists():
        return data
    for line in env_path.read_text(encoding='utf-8').splitlines():
        line = line.strip()
        if not line or line.startswith('#') or '=' not in line:
            continue
        key, value = line.split('=', 1)
        data[key.strip()] = value.strip()
    return data


def get_mysql_connector():
    try:
        import mysql.connector  # type: ignore
        return mysql.connector
    except Exception:
        print('mysql-connector-python is required. Install with: pip install mysql-connector-python', file=sys.stderr)
        sys.exit(1)


def build_privacy_ko() -> str:
    return """
<h1>랜덤질문 개인정보 처리방침</h1>

<p>brosister(이하 \"회사\")는 개인정보보호법에 따라 이용자의 개인정보를 보호하고 관련 고충을 신속하고 원활하게 처리하기 위해 다음과 같이 개인정보 처리방침을 수립·공개합니다.</p>

<h2>제1조 (수집하는 개인정보 항목)</h2>
<div class="highlight">
<p><strong>랜덤질문은 회원가입 없이 이용할 수 있으며, 서비스 제공에 필요한 최소한의 정보만 처리하거나 개인정보를 수집하지 않을 수 있습니다.</strong></p>
</div>
<ul>
  <li>기기 내 설정값, 게임 진행 기록, 로컬 사용 기록 등은 사용자 기기에 저장될 수 있습니다.</li>
  <li>앱 품질 개선을 위해 익명화된 앱 사용 정보가 활용될 수 있습니다.</li>
  <li>광고 제공을 위해 Google AdMob 정책에 따른 광고 식별자가 사용될 수 있습니다.</li>
</ul>

<h2>제2조 (개인정보의 처리 목적)</h2>
<ul>
  <li>질문 카드 및 게임형 질문 콘텐츠 기능 제공</li>
  <li>앱 설정, 최근 기록 등 사용자 경험 유지</li>
  <li>광고 표시 및 서비스 품질 개선</li>
</ul>

<h2>제3조 (보유 및 이용 기간)</h2>
<ul>
  <li>기기 내부에 저장된 데이터는 사용자가 앱을 삭제하거나 초기화할 때 삭제될 수 있습니다.</li>
  <li>회사가 직접 보관하는 개인정보가 있는 경우 관련 법령 또는 목적 달성 시까지 최소 범위에서 보관합니다.</li>
</ul>

<h2>제4조 (제3자 제공)</h2>
<p>회사는 이용자의 개인정보를 원칙적으로 외부에 제공하지 않습니다. 다만 법령에 근거한 요청이 있는 경우 예외가 있을 수 있습니다.</p>

<h2>제5조 (광고 및 외부 서비스)</h2>
<ul>
  <li>본 앱은 Google AdMob을 통한 배너 광고 또는 전면 광고를 표시할 수 있습니다.</li>
  <li>광고 처리 방식은 Google 정책을 따르며, 자세한 내용은 <a href="https://policies.google.com/privacy" target="_blank">Google 개인정보 처리방침</a>을 참조하세요.</li>
</ul>

<h2>제6조 (이용자의 권리)</h2>
<ul>
  <li>이용자는 앱 삭제 또는 설정 초기화를 통해 기기 내 저장 데이터를 제거할 수 있습니다.</li>
  <li>광고 개인화는 기기 설정에서 변경할 수 있습니다.</li>
</ul>

<h2>제7조 (개인정보 보호책임자)</h2>
<table>
  <tr><th>항목</th><th>내용</th></tr>
  <tr><td>회사명</td><td>brosister</td></tr>
  <tr><td>담당자</td><td>이상현</td></tr>
  <tr><td>이메일</td><td>admin@officialsite.kr</td></tr>
  <tr><td>웹사이트</td><td><a href="https://brosister.officialsite.kr">https://brosister.officialsite.kr</a></td></tr>
</table>

<h2>제8조 (개인정보 처리방침 변경)</h2>
<p>본 방침은 법령, 정책 또는 보안기술의 변경에 따라 수정될 수 있으며, 변경 시 앱 또는 관련 페이지를 통해 안내합니다.</p>
""".strip()


def build_privacy_en() -> str:
    return """
<h1>Random Question Privacy Policy</h1>

<p>brosister (the \"Company\") establishes and discloses the following privacy policy to protect users' personal information and handle related matters promptly.</p>

<h2>1. Information We Collect</h2>
<div class="highlight">
<p><strong>Random Question may work without account registration and may collect no personal information or only the minimum information required to provide the service.</strong></p>
</div>
<ul>
  <li>Settings, game progress, and local usage records may be stored on the user's device.</li>
  <li>Anonymized usage data may be used to improve app quality.</li>
  <li>Advertising identifiers may be used according to Google AdMob policies.</li>
</ul>

<h2>2. Purpose of Processing</h2>
<ul>
  <li>Providing question cards and game-style question content</li>
  <li>Maintaining app settings and recent history</li>
  <li>Displaying ads and improving service quality</li>
</ul>

<h2>3. Retention Period</h2>
<ul>
  <li>Data stored on the device may be removed when the app is deleted or reset by the user.</li>
  <li>If any personal information is retained by the Company, it is kept only as required by law or until the purpose is fulfilled.</li>
</ul>

<h2>4. Sharing with Third Parties</h2>
<p>The Company does not provide personal information to third parties except where required by law.</p>

<h2>5. Advertising and External Services</h2>
<ul>
  <li>This app may display banner or interstitial ads through Google AdMob.</li>
  <li>Ad processing follows Google's policies. For details, please refer to <a href="https://policies.google.com/privacy" target="_blank">Google's Privacy Policy</a>.</li>
</ul>

<h2>6. User Rights</h2>
<ul>
  <li>Users may remove locally stored data by deleting the app or resetting app settings.</li>
  <li>Ad personalization can be managed in device settings.</li>
</ul>

<h2>7. Privacy Contact</h2>
<table>
  <tr><th>Item</th><th>Details</th></tr>
  <tr><td>Company</td><td>brosister</td></tr>
  <tr><td>Contact</td><td>Sanghyun Lee</td></tr>
  <tr><td>Email</td><td>admin@officialsite.kr</td></tr>
  <tr><td>Website</td><td><a href="https://brosister.officialsite.kr">https://brosister.officialsite.kr</a></td></tr>
</table>

<h2>8. Changes to This Policy</h2>
<p>This policy may be updated due to changes in laws, policies, or security technologies. Any changes will be announced through the app or related pages.</p>
""".strip()


def upsert_setting(cursor):
    cursor.execute(
        "SELECT id FROM app_settings WHERE app_name = %s AND setting_key = 'privacy_url' LIMIT 1",
        ('randomquestion',),
    )
    row = cursor.fetchone()
    url = 'https://app-master.officialsite.kr/privacy/randomquestion'
    if row:
        cursor.execute(
            """
            UPDATE app_settings
            SET setting_value = %s,
                description = '개인정보처리방침 URL',
                updated_at = NOW()
            WHERE id = %s
            """,
            (url, row[0]),
        )
        print('Updated app_settings privacy_url')
    else:
        cursor.execute(
            """
            INSERT INTO app_settings (app_name, setting_key, setting_value, description)
            VALUES (%s, 'privacy_url', %s, '개인정보처리방침 URL')
            """,
            ('randomquestion', url),
        )
        print('Inserted app_settings privacy_url')


def upsert_policy(cursor, language_code: str, title: str, content: str):
    cursor.execute(
        """
        SELECT id
        FROM app_policies
        WHERE app_name = %s AND policy_type = 'privacy' AND language_code = %s
        ORDER BY effective_date DESC, id DESC
        LIMIT 1
        """,
        ('randomquestion', language_code),
    )
    row = cursor.fetchone()
    if row:
        cursor.execute(
            """
            UPDATE app_policies
            SET title = %s,
                content = %s,
                version = '1.0',
                effective_date = '2026-03-20',
                updated_at = NOW()
            WHERE id = %s
            """,
            (title, content, row[0]),
        )
        print(f'Updated app_policies ({language_code})')
    else:
        cursor.execute(
            """
            INSERT INTO app_policies
            (app_name, policy_type, language_code, title, content, version, effective_date)
            VALUES (%s, 'privacy', %s, %s, %s, '1.0', '2026-03-20')
            """,
            ('randomquestion', language_code, title, content),
        )
        print(f'Inserted app_policies ({language_code})')


def main():
    env_path = Path(__file__).with_name('.env')
    env = {**os.environ, **load_env(env_path)}

    db_host = env.get('DB_HOST')
    db_user = env.get('DB_USER')
    db_password = env.get('DB_PASSWORD')
    db_port = int(env.get('DB_PORT', '3306'))
    db_name = env.get('DB_NAME')

    if not all([db_host, db_user, db_password, db_name]):
        print('Missing DB_* settings. Check your .env file.', file=sys.stderr)
        sys.exit(1)

    mysql = get_mysql_connector()
    conn = mysql.connect(
        host=db_host,
        user=db_user,
        password=db_password,
        port=db_port,
        database=db_name,
        charset='utf8mb4',
    )
    cursor = conn.cursor()

    upsert_setting(cursor)
    upsert_policy(cursor, 'ko', '랜덤질문 개인정보 처리방침', build_privacy_ko())
    upsert_policy(cursor, 'en', 'Random Question Privacy Policy', build_privacy_en())

    conn.commit()
    cursor.close()
    conn.close()
    print('RandomQuestion privacy URL/policy synced successfully.')


if __name__ == '__main__':
    main()
