#!/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>
<p>증거노트는 약속, 거래, 정산, 차용, 반납 등 개인 기록을 정리하고 첨부 파일과 함께 보관할 수 있도록 돕는 앱입니다.</p>

<h2>제2조 (수집 또는 처리하는 정보)</h2>
<ul>
  <li>사용자가 직접 입력한 제목, 상대 이름, 금액, 날짜, 메모, 상태 정보</li>
  <li>사용자가 첨부한 사진, 음성 녹음, 서명 이미지</li>
  <li>기기 식별용 값(device serial) 및 앱 내부 사용자 식별값</li>
  <li>PDF 내보내기 기록 및 첨부 업로드 처리에 필요한 최소한의 메타데이터</li>
  <li>광고 제공을 위한 Google AdMob 관련 설정 조회 정보</li>
</ul>

<h2>제3조 (이용 목적)</h2>
<ul>
  <li>약속/거래 기록 저장 및 동기화</li>
  <li>첨부 파일 업로드 및 기록 연결</li>
  <li>PDF 생성/내보내기 기능 제공</li>
  <li>광고 설정 적용 및 서비스 운영</li>
  <li>오류 확인과 서비스 품질 개선</li>
</ul>

<h2>제4조 (첨부 파일 업로드 및 외부 저장소)</h2>
<ul>
  <li>사용자가 업로드한 첨부 파일은 NCP Object Storage(S3 호환 저장소)에 저장될 수 있습니다.</li>
  <li>현재 구현 기준으로 업로드 객체는 기본적으로 <strong>private ACL</strong>로 처리됩니다.</li>
  <li>서비스 제공 과정에서 CDN 주소 또는 내부 저장 키가 메타데이터로 함께 기록될 수 있습니다.</li>
</ul>

<h2>제5조 (보관 기간)</h2>
<ul>
  <li>기기 내부에 저장된 데이터는 사용자가 직접 삭제하거나 앱을 제거할 때 제거될 수 있습니다.</li>
  <li>서버에 저장된 기록 및 업로드 메타데이터는 서비스 운영, 동기화, 복구, 품질 관리 목적 범위 내에서 보관될 수 있습니다.</li>
</ul>

<h2>제6조 (제3자 제공 및 외부 서비스)</h2>
<ul>
  <li>회사는 법령에 따른 경우를 제외하고 사용자의 개인정보를 임의로 제3자에게 판매하거나 제공하지 않습니다.</li>
  <li>광고 처리에는 Google AdMob이 사용될 수 있습니다.</li>
  <li>자세한 내용은 <a href=\"https://policies.google.com/privacy\" target=\"_blank\">Google 개인정보 처리방침</a>을 참조하세요.</li>
</ul>

<h2>제7조 (유의사항)</h2>
<p>증거노트는 개인 기록 정리 및 보관을 돕는 도구이며, 앱 내 기록/타임스탬프/해시/첨부 파일만으로 특정 법적 효력이나 공증 수준을 보장하지 않습니다.</p>

<h2>제8조 (문의처)</h2>
<p>이메일: admin@officialsite.kr</p>
""".strip()


def privacy_en() -> str:
    return """
<h1>Evidence Note Privacy Policy</h1>
<p>brosister (the \"Company\") publishes this privacy policy to protect users' personal information.</p>

<h2>1. Service Overview</h2>
<p>Evidence Note helps users organize personal records such as promises, transactions, settlements, borrowing, and returns together with related attachments.</p>

<h2>2. Information We Collect or Process</h2>
<ul>
  <li>Titles, counterparty names, amounts, dates, memos, and status values entered by the user</li>
  <li>Photos, voice recordings, and signature images uploaded by the user</li>
  <li>Device serial values and internal user identifiers used for app operation</li>
  <li>Minimum metadata required for PDF export logs and attachment uploads</li>
  <li>Ad configuration retrieval data related to Google AdMob</li>
</ul>

<h2>3. Purpose of Use</h2>
<ul>
  <li>Saving and syncing promise/transaction records</li>
  <li>Uploading attachments and linking them to records</li>
  <li>Providing PDF generation/export features</li>
  <li>Applying ad settings and operating the service</li>
  <li>Checking errors and improving service quality</li>
</ul>

<h2>4. Attachment Uploads and External Storage</h2>
<ul>
  <li>User-uploaded attachments may be stored in NCP Object Storage (S3-compatible storage).</li>
  <li>Under the current implementation, uploaded objects are handled with a <strong>private ACL</strong> by default.</li>
  <li>CDN URLs or internal storage keys may be stored together as metadata for service operation.</li>
</ul>

<h2>5. Retention</h2>
<ul>
  <li>Data stored on the device may be removed when the user deletes it or removes the app.</li>
  <li>Server-stored records and upload metadata may be retained within the scope necessary for operation, sync, recovery, and quality management.</li>
</ul>

<h2>6. Third Parties and External Services</h2>
<ul>
  <li>The Company does not sell or arbitrarily provide personal information to third parties except where required by law.</li>
  <li>Google AdMob may be used for advertising.</li>
  <li>Please refer to the <a href=\"https://policies.google.com/privacy\" target=\"_blank\">Google Privacy Policy</a> for more details.</li>
</ul>

<h2>7. Important Notice</h2>
<p>Evidence Note is a tool for organizing and storing personal records. Records, timestamps, hashes, and attachments in the app do not by themselves guarantee any specific legal effect or notarization level.</p>

<h2>8. Contact</h2>
<p>Email: admin@officialsite.kr</p>
""".strip()


def upsert_setting(cursor):
    url = 'https://app-master.officialsite.kr/privacy/evidence-note'
    cursor.execute("SELECT id FROM app_settings WHERE app_name = %s AND setting_key = 'privacy_url' LIMIT 1", ('evidence-note',))
    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')",
            ('evidence-note', 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",
        ('evidence-note', language_code),
    )
    row = cursor.fetchone()
    if row:
        cursor.execute(
            "UPDATE app_policies SET title=%s, content=%s, version='1.0', effective_date='2026-04-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-04-06')",
            ('evidence-note', 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', 'Evidence Note Privacy Policy', privacy_en())
    conn.commit()
    cursor.close()
    conn.close()
    print('Evidence Note privacy URL/policy synced successfully.')


if __name__ == '__main__':
    main()
