#!/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 privacy_ko() -> str:
    return """
<h1>지갑지켜 개인정보 처리방침</h1>
<p>brosister(이하 "회사")는 이용자의 개인정보를 보호하기 위해 다음과 같이 개인정보 처리방침을 공개합니다.</p>
<h2>제1조 (수집하는 정보)</h2>
<ul>
  <li>지갑지켜는 회원가입 없이 이용할 수 있으며, 수입/지출 기록은 기본적으로 사용자의 기기 내부에 저장됩니다.</li>
  <li>앱 품질 개선을 위해 익명화된 진단 정보가 활용될 수 있습니다.</li>
  <li>광고 제공 시 Google AdMob 정책에 따른 광고 식별자가 사용될 수 있습니다.</li>
</ul>
<h2>제2조 (이용 목적)</h2>
<ul>
  <li>가계부 기록, 지출 관리, 예산 흐름 확인 기능 제공</li>
  <li>앱 품질 개선 및 오류 분석</li>
  <li>광고 표시 및 서비스 운영</li>
</ul>
<h2>제3조 (보관 기간)</h2>
<p>회사가 직접 보관하는 개인정보가 없는 경우 즉시 파기되며, 기기 내 정보는 앱 삭제 시 제거될 수 있습니다.</p>
<h2>제4조 (제3자 제공)</h2>
<p>회사는 법령에 따른 경우를 제외하고 개인정보를 외부에 제공하지 않습니다.</p>
<h2>제5조 (외부 서비스)</h2>
<ul>
  <li>광고 처리에는 Google AdMob이 사용될 수 있습니다.</li>
  <li>자세한 내용은 <a href="https://policies.google.com/privacy" target="_blank">Google 개인정보 처리방침</a>을 참조하세요.</li>
</ul>
<h2>제6조 (문의처)</h2>
<p>이메일: admin@officialsite.kr</p>
""".strip()


def privacy_en() -> str:
    return """
<h1>Wallet Keeper Privacy Policy</h1>
<p>brosister (the "Company") discloses this privacy policy to protect users' personal information.</p>
<h2>1. Information We Collect</h2>
<ul>
  <li>Wallet Keeper can be used without account registration, and income/expense records are primarily stored on the user's device.</li>
  <li>Anonymous diagnostic information 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 Use</h2>
<ul>
  <li>Providing household ledger records, expense tracking, and budget overview features</li>
  <li>Improving app quality and analyzing errors</li>
  <li>Displaying ads and operating the service</li>
</ul>
<h2>3. Retention</h2>
<p>If no personal information is retained by the Company, it is discarded immediately. Data stored on the device may be removed when the app is deleted.</p>
<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. External Services</h2>
<ul>
  <li>Google AdMob may be used for advertising.</li>
  <li>See <a href="https://policies.google.com/privacy" target="_blank">Google Privacy Policy</a> for more details.</li>
</ul>
<h2>6. Contact</h2>
<p>Email: admin@officialsite.kr</p>
""".strip()


def upsert_setting(cursor):
    url = 'https://app-master.officialsite.kr/privacy/wallet-keeper'
    cursor.execute("SELECT id FROM app_settings WHERE app_name = %s AND setting_key = 'privacy_url' LIMIT 1", ('wallet_keeper',))
    row = cursor.fetchone()
    if row:
        cursor.execute(
            "UPDATE app_settings SET setting_value=%s, description='개인정보처리방침 URL', updated_at=NOW() WHERE id=%s",
            (url, row[0]),
        )
    else:
        cursor.execute(
            "INSERT INTO app_settings (app_name, setting_key, setting_value, description) VALUES (%s, 'privacy_url', %s, '개인정보처리방침 URL')",
            ('wallet_keeper', 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",
        ('wallet_keeper', language_code),
    )
    row = cursor.fetchone()
    if row:
        cursor.execute(
            "UPDATE app_policies SET title=%s, content=%s, version='1.0', effective_date='2026-05-06', updated_at=NOW() WHERE id=%s",
            (title, content, row[0]),
        )
    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-05-06')",
            ('wallet_keeper', language_code, title, content),
        )


def main():
    env = {**os.environ, **load_env(Path(__file__).with_name('.env'))}
    required = ['DB_HOST', 'DB_USER', 'DB_PASSWORD', 'DB_NAME']
    if not all(env.get(key) for key in required):
        print('Missing DB_* settings. Check your .env or environment variables.', file=sys.stderr)
        sys.exit(1)

    mysql = get_mysql_connector()
    conn = mysql.connect(
        host=env['DB_HOST'],
        user=env['DB_USER'],
        password=env['DB_PASSWORD'],
        port=int(env.get('DB_PORT', '23306')),
        database=env['DB_NAME'],
        charset='utf8mb4',
    )
    cursor = conn.cursor()
    upsert_setting(cursor)
    upsert_policy(cursor, 'ko', '지갑지켜 개인정보 처리방침', privacy_ko())
    upsert_policy(cursor, 'en', 'Wallet Keeper Privacy Policy', privacy_en())
    conn.commit()
    cursor.close()
    conn.close()
    print('Wallet Keeper privacy URL/policy synced successfully.')


if __name__ == '__main__':
    main()
