#!/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>Named 개인정보 처리방침</h1>

<div class="highlight">
<strong>시행일자:</strong> 2026년 04월 21일<br>
<strong>최종 수정일:</strong> 2026년 04월 21일
</div>

<h2>1. 개인정보의 처리목적</h2>
<p>Named는 디지털 명함 제작, 보관, 공유 및 전자서명 기능 제공을 위해 필요한 범위에서 개인정보를 처리합니다.</p>
<ul>
<li>내 명함 및 일반 명함 저장, 조회, 수정, 삭제</li>
<li>명함 앞면/뒷면 디자인 및 캔버스 편집 기능 제공</li>
<li>전자서명 생성, 저장, 수정, 삭제</li>
<li>이미지 업로드 및 저장 파일 관리</li>
<li>기기별 데이터 구분과 서비스 운영 안정성 확보</li>
<li>광고 노출 및 서비스 이용 환경 제공</li>
</ul>

<h2>2. 수집하는 개인정보 항목</h2>
<h3>2-1. 이용자가 직접 입력하거나 생성하는 정보</h3>
<ul>
<li><strong>명함 정보:</strong> 이름, 직책, 회사명, 휴대폰, 유선전화, 팩스, 이메일, 주소, 웹사이트 등 이용자가 입력한 정보</li>
<li><strong>디자인 정보:</strong> 텍스트, 글꼴, 색상, 이미지, 도형, 배경, 앞면/뒷면 캔버스 구성 정보</li>
<li><strong>전자서명 정보:</strong> 서명 이미지, 서명명, 캔버스 설정 정보</li>
<li><strong>업로드 파일:</strong> 이용자가 명함 또는 전자서명에 사용하기 위해 업로드한 이미지 파일</li>
</ul>

<h3>2-2. 서비스 제공 과정에서 처리되는 정보</h3>
<ul>
<li><strong>기기 식별값:</strong> 기기별 데이터 구분을 위한 Android ID 또는 이에 준하는 식별값</li>
<li><strong>저장 메타데이터:</strong> 생성일시, 수정일시, 저장 경로 키, 파일 URL 등 서비스 운영에 필요한 최소 정보</li>
<li><strong>광고 관련 정보:</strong> Google AdMob을 통한 광고 제공 과정에서 처리되는 광고 식별자 및 광고 요청 정보</li>
</ul>

<h2>3. 개인정보의 처리 및 보유기간</h2>
<ul>
<li><strong>명함 데이터 및 전자서명 데이터:</strong> 이용자가 직접 삭제하기 전까지 또는 서비스 운영상 필요한 기간 동안 보관될 수 있습니다.</li>
<li><strong>업로드 파일 및 관련 메타데이터:</strong> 이용자가 삭제 요청을 하거나 해당 데이터가 더 이상 필요하지 않을 때까지 보관될 수 있습니다.</li>
<li><strong>기기 식별값:</strong> 기기별 데이터 구분 목적이 필요한 기간 동안 보관될 수 있습니다.</li>
<li><strong>광고 관련 데이터:</strong> Google AdMob 및 관련 정책에 따릅니다.</li>
</ul>

<h2>4. 개인정보의 제3자 제공</h2>
<p>회사는 원칙적으로 이용자의 개인정보를 외부에 판매하거나 임의 제공하지 않습니다. 다만 다음과 같은 외부 서비스가 이용될 수 있습니다.</p>
<ul>
<li><strong>Google AdMob:</strong> 광고 제공</li>
<li><strong>백엔드 API 및 저장소 인프라:</strong> 명함/전자서명 데이터 및 업로드 파일 저장·관리</li>
<li><strong>법적 요구사항:</strong> 관련 법령에 의거한 요구가 있는 경우</li>
</ul>

<h2>5. 개인정보 처리 위탁</h2>
<table border="1">
<tr><th>수탁업체</th><th>위탁업무</th><th>개인정보 보유기간</th></tr>
<tr><td>Google AdMob</td><td>광고 서비스 제공</td><td>관련 정책에 따름</td></tr>
<tr><td>서비스 운영 서버 및 스토리지</td><td>명함/전자서명 데이터 및 업로드 파일 저장·관리</td><td>서비스 운영상 필요한 기간 또는 사용자 삭제 시점까지</td></tr>
</table>

<h2>6. 이용자의 권리</h2>
<p>이용자는 언제든지 다음과 같은 권리를 행사할 수 있습니다.</p>
<ul>
<li>앱 내에서 명함 및 전자서명 데이터를 직접 확인, 수정, 삭제할 수 있습니다.</li>
<li>저장된 명함 또는 전자서명을 이미지로 저장하거나 공유할 수 있습니다.</li>
<li>개인정보 처리와 관련한 문의를 이메일로 요청할 수 있습니다.</li>
</ul>

<h2>7. 개인정보의 안전성 확보조치</h2>
<ul>
<li>암호화 통신 등 일반적인 보안 조치를 적용할 수 있습니다.</li>
<li>서비스 운영에 필요한 범위에서 접근 권한을 관리합니다.</li>
<li>시스템 안정성 확보를 위한 점검 및 업데이트를 수행할 수 있습니다.</li>
</ul>

<h2>8. 개인정보의 파기</h2>
<ul>
<li>이용자가 앱 내에서 삭제한 명함 및 전자서명 데이터는 서비스 시스템에서 순차적으로 제거될 수 있습니다.</li>
<li>업로드 파일은 관련 데이터 삭제 또는 운영상 정리 절차에 따라 제거될 수 있습니다.</li>
</ul>

<h2>9. 개인정보 보호책임자</h2>
<ul>
<li><strong>상호:</strong> BroSister</li>
<li><strong>연락처:</strong> admin@officialsite.kr</li>
<li><strong>웹사이트:</strong> brosister.officialsite.kr</li>
</ul>

<h2>10. 고지의무</h2>
<p>본 개인정보 처리방침은 서비스 기능 또는 관련 법령의 변경에 따라 수정될 수 있으며, 중요한 변경 사항은 앱 또는 관련 페이지를 통해 안내합니다.</p>
""".strip()


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

<div class="highlight">
<strong>Effective Date:</strong> April 21, 2026<br>
<strong>Last Updated:</strong> April 21, 2026
</div>

<h2>1. Purpose of Personal Information Processing</h2>
<p>Named processes personal information within the scope necessary to provide digital business card creation, storage, sharing, and electronic signature features.</p>
<ul>
<li>Saving, viewing, editing, and deleting primary and regular business cards</li>
<li>Providing front/back card design and canvas editing features</li>
<li>Creating, saving, editing, and deleting electronic signatures</li>
<li>Managing uploaded images and stored files</li>
<li>Separating device-scoped data and maintaining service stability</li>
<li>Providing advertising and service operation environment</li>
</ul>

<h2>2. Personal Information Items Collected</h2>
<h3>2-1. Information entered or created by the user</h3>
<ul>
<li><strong>Business Card Information:</strong> Name, title, company, mobile phone, landline, fax, email, address, website, and other information entered by the user</li>
<li><strong>Design Information:</strong> Text, fonts, colors, images, shapes, backgrounds, and front/back canvas composition</li>
<li><strong>Electronic Signature Information:</strong> Signature images, signature names, and canvas configuration</li>
<li><strong>Uploaded Files:</strong> Image files uploaded for business cards or signatures</li>
</ul>

<h3>2-2. Information processed during service operation</h3>
<ul>
<li><strong>Device Identifier:</strong> Android ID or an equivalent value used to distinguish device-scoped data</li>
<li><strong>Storage Metadata:</strong> Created/updated timestamps, storage keys, file URLs, and other minimum data required for operation</li>
<li><strong>Advertising Data:</strong> Advertising identifiers and ad request information processed through Google AdMob</li>
</ul>

<h2>3. Retention Period</h2>
<ul>
<li><strong>Business card and signature data:</strong> May be retained until deleted by the user or as needed for service operation</li>
<li><strong>Uploaded files and related metadata:</strong> May be retained until deletion is requested or no longer needed</li>
<li><strong>Device identifier:</strong> May be retained as long as needed to separate device-scoped data</li>
<li><strong>Advertising data:</strong> Subject to Google AdMob and related policies</li>
</ul>

<h2>4. Third-Party Sharing</h2>
<p>We do not sell or arbitrarily provide personal information to third parties. However, the following external services may be used:</p>
<ul>
<li><strong>Google AdMob:</strong> Ad delivery</li>
<li><strong>Backend API and storage infrastructure:</strong> Storage and management of business card/signature data and uploaded files</li>
<li><strong>Legal Requirements:</strong> When required under applicable law</li>
</ul>

<h2>5. Data Processing Consignment</h2>
<table border="1">
<tr><th>Consignee</th><th>Consigned Work</th><th>Retention Period</th></tr>
<tr><td>Google AdMob</td><td>Advertising services</td><td>According to related policies</td></tr>
<tr><td>Service backend and storage</td><td>Storage and management of business card/signature data and uploaded files</td><td>As needed for operation or until user deletion</td></tr>
</table>

<h2>6. User Rights</h2>
<p>Users may exercise the following rights at any time:</p>
<ul>
<li>Review, edit, and delete business card and signature data within the app</li>
<li>Save or share stored cards and signatures as images</li>
<li>Contact us by email regarding personal information processing</li>
</ul>

<h2>7. Security Measures</h2>
<ul>
<li>General security measures such as encrypted communication may be applied</li>
<li>Access permissions are managed within the scope necessary for service operation</li>
<li>System checks and updates may be performed to maintain stability</li>
</ul>

<h2>8. Data Destruction</h2>
<ul>
<li>Business card and signature data deleted by the user may be removed from the service system in sequence</li>
<li>Uploaded files may be removed when related data is deleted or during operational cleanup</li>
</ul>

<h2>9. Privacy Contact</h2>
<ul>
<li><strong>Company:</strong> BroSister</li>
<li><strong>Contact:</strong> admin@officialsite.kr</li>
<li><strong>Website:</strong> brosister.officialsite.kr</li>
</ul>

<h2>10. Policy Changes</h2>
<p>This privacy policy may be updated to reflect changes in service features or applicable laws, and material changes will be announced through the app or related pages.</p>
""".strip()


def upsert_setting(cursor):
    url = 'https://app-master.officialsite.kr/privacy/named'
    cursor.execute("SELECT id FROM app_settings WHERE app_name = %s AND setting_key = 'privacy_url' LIMIT 1", ('named',))
    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')",
            ('named', 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",
        ('named', language_code),
    )
    row = cursor.fetchone()
    if row:
        cursor.execute(
            "UPDATE app_policies SET title=%s, content=%s, version='1.0', effective_date='2026-04-21', 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-21')",
            ('named', language_code, title, content),
        )


def main():
    env_files = [
        Path(__file__).with_name('.env'),
        Path(__file__).resolve().parent.parent / '.env',
    ]
    loaded_env = {}
    for env_file in env_files:
        loaded_env.update(load_env(env_file))

    env = {**os.environ, **loaded_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', 'Named 개인정보 처리방침', privacy_ko())
    upsert_policy(cursor, 'en', 'Named Privacy Policy', privacy_en())
    conn.commit()
    cursor.close()
    conn.close()
    print('Named privacy URL/policy synced successfully.')


if __name__ == '__main__':
    main()
