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


APP_NAME = "pill-reminder"
EFFECTIVE_DATE = "2026-04-15"
VERSION = "1.0"


def load_env(env_path: Path) -> dict:
    data: dict[str, str] = {}
    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(이하 &quot;회사&quot;)는 개인정보보호법 등 관련 법령을 준수하며 이용자의 개인정보를 보호하기 위해 다음과 같이 개인정보 처리방침을 수립·공개합니다.</p>

<h2>제1조 (서비스 개요)</h2>
<p>약 알리미는 복약(약 복용) 시간 알림과 복용 체크, 간단한 기록 관리 기능을 제공하는 앱입니다.</p>

<h2>제2조 (수집 또는 처리하는 정보)</h2>
<div class="highlight">
<p><strong>약 알리미는 회원가입 없이 이용할 수 있으며, 사용자가 앱에 입력한 복약 관련 정보는 기본적으로 사용자의 기기 내에 저장됩니다.</strong></p>
</div>
<ul>
  <li><strong>사용자 입력 정보(기기 내 저장)</strong>: 약 이름, 1일 목표 복용 횟수, 복용/건너뜀 체크, 간단한 로그(기록) 등</li>
  <li><strong>알림 기능</strong>: 복약 알림 제공을 위해 기기의 알림 권한이 사용될 수 있습니다.</li>
  <li><strong>네트워크 요청</strong>: 광고 설정(AdMob 설정값) 조회를 위해 회사 서버에 요청할 수 있으며, 이 과정에서 서버 접속 로그(예: IP 주소, 접속일시, User-Agent 등)가 자동 생성될 수 있습니다.</li>
  <li><strong>광고 식별자</strong>: 광고 제공을 위해 Google AdMob이 사용될 수 있으며, Google 정책에 따라 광고 식별자(Advertising ID/IDFA 등)가 처리될 수 있습니다.</li>
</ul>

<h2>제3조 (개인정보의 처리 목적)</h2>
<ul>
  <li>복약 알림 및 복용 체크 기능 제공</li>
  <li>앱 설정(알림 주기, 시작 시간 등) 및 기록 유지</li>
  <li>광고 표시 및 서비스 운영</li>
  <li>오류 확인, 보안, 서비스 품질 개선</li>
</ul>

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

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

<h2>제6조 (외부 서비스 및 광고)</h2>
<ul>
  <li>본 앱은 Google AdMob을 통한 배너/전면 광고를 표시할 수 있습니다.</li>
  <li>Google이 처리하는 정보 및 이용자의 선택권(광고 개인화 등)에 대한 자세한 내용은 <a href="https://policies.google.com/privacy" target="_blank" rel="noopener noreferrer">Google 개인정보 처리방침</a>을 참조하세요.</li>
</ul>

<h2>제7조 (이용자의 권리 및 선택)</h2>
<ul>
  <li>이용자는 앱 삭제 또는 앱 데이터 초기화를 통해 기기 내 저장 데이터를 제거할 수 있습니다.</li>
  <li>알림 수신은 기기 설정 또는 앱 내 설정에서 변경할 수 있습니다.</li>
  <li>광고 개인화 설정은 기기 설정(예: 광고 ID 재설정/개인 맞춤형 광고 제한)에서 변경할 수 있습니다.</li>
</ul>

<h2>제8조 (문의처)</h2>
<table>
  <tr><th>항목</th><th>내용</th></tr>
  <tr><td>회사명</td><td>brosister</td></tr>
  <tr><td>이메일</td><td>admin@officialsite.kr</td></tr>
  <tr><td>웹사이트</td><td><a href="https://brosister.officialsite.kr" target="_blank" rel="noopener noreferrer">https://brosister.officialsite.kr</a></td></tr>
</table>

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


def privacy_en() -> str:
    return """
<h1>Pill Reminder Privacy Policy</h1>

<p>brosister (the &quot;Company&quot;) complies with applicable privacy laws and publishes this policy to protect users&apos; personal information.</p>

<h2>1. Service Overview</h2>
<p>Pill Reminder provides medication reminder notifications, dose check-off, and simple history/log features.</p>

<h2>2. Information We Collect or Process</h2>
<div class="highlight">
<p><strong>Pill Reminder can be used without account registration, and medication-related information entered in the app is stored on the user&apos;s device by default.</strong></p>
</div>
<ul>
  <li><strong>User-provided data (stored on device)</strong>: medication names, daily dose goals, taken/skipped status, and simple logs (history)</li>
  <li><strong>Notifications</strong>: notification permission may be used to deliver scheduled medication reminders.</li>
  <li><strong>Network requests</strong>: the app may request the Company&apos;s server to retrieve advertising settings (AdMob configuration). During this process, server access logs (e.g., IP address, access time, User-Agent) may be generated automatically.</li>
  <li><strong>Advertising identifiers</strong>: Google AdMob may be used for ads, and advertising identifiers (Advertising ID/IDFA, etc.) may be processed in accordance with Google policies.</li>
</ul>

<h2>3. Purpose of Processing</h2>
<ul>
  <li>Providing medication reminders and dose check-off features</li>
  <li>Maintaining app settings (reminder interval, start time, etc.) and local history</li>
  <li>Displaying ads and operating the service</li>
  <li>Security, debugging, and improving service quality</li>
</ul>

<h2>4. Retention</h2>
<ul>
  <li>Data stored on the device may be removed when the user deletes the app or resets app data.</li>
  <li>If any personal information is retained by the Company, it will be retained only as required by law or until the purpose is fulfilled, within the minimum necessary scope.</li>
</ul>

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

<h2>6. External Services and Advertising</h2>
<ul>
  <li>This app may display banner/interstitial ads through Google AdMob.</li>
  <li>For details on information processed by Google and user choices (e.g., ad personalization), please refer to <a href="https://policies.google.com/privacy" target="_blank" rel="noopener noreferrer">Google&apos;s Privacy Policy</a>.</li>
</ul>

<h2>7. User Rights and Choices</h2>
<ul>
  <li>Users can remove locally stored data by deleting the app or resetting app data.</li>
  <li>Notification settings can be changed in device settings or in the app.</li>
  <li>Ad personalization can be managed in device settings (e.g., reset advertising ID / limit ad personalization).</li>
</ul>

<h2>8. Contact</h2>
<table>
  <tr><th>Item</th><th>Details</th></tr>
  <tr><td>Company</td><td>brosister</td></tr>
  <tr><td>Email</td><td>admin@officialsite.kr</td></tr>
  <tr><td>Website</td><td><a href="https://brosister.officialsite.kr" target="_blank" rel="noopener noreferrer">https://brosister.officialsite.kr</a></td></tr>
</table>

<h2>9. Changes to This Policy</h2>
<p>This policy may be updated due to changes in laws, policies, or the service. Updates will be announced on the relevant page.</p>
""".strip()


def upsert_setting(cursor, base_url: str):
    url = f"{base_url}/privacy/{APP_NAME}"
    cursor.execute(
        "SELECT id FROM app_settings WHERE app_name = %s AND setting_key = 'privacy_url' LIMIT 1",
        (APP_NAME,),
    )
    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]),
        )
        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')",
            (APP_NAME, 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 LIMIT 1",
        (APP_NAME, language_code),
    )
    row = cursor.fetchone()
    if row:
        cursor.execute(
            "UPDATE app_policies SET title=%s, content=%s, version=%s, effective_date=%s, updated_at=NOW() WHERE id=%s",
            (title, content, VERSION, EFFECTIVE_DATE, 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, %s, %s)",
            (APP_NAME, language_code, title, content, VERSION, EFFECTIVE_DATE),
        )
        print(f"Inserted app_policies ({language_code})")


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)

    base_url = (env.get("BASE_URL") or "https://app-master.officialsite.kr").rstrip("/")

    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, base_url)
    upsert_policy(cursor, "ko", "약 알리미 개인정보 처리방침", privacy_ko())
    upsert_policy(cursor, "en", "Pill Reminder Privacy Policy", privacy_en())
    conn.commit()
    cursor.close()
    conn.close()
    print("Pill Reminder privacy URL/policy synced successfully.")


if __name__ == "__main__":
    main()

