#!/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 terms_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>이 약관은 BroSister(이하 "회사")가 제공하는 Named 앱 서비스의 이용조건, 절차, 회사와 이용자 간의 권리·의무 및 책임사항을 규정하는 것을 목적으로 합니다.</p>

<h2>제2조 (서비스 내용)</h2>
<p>회사는 다음 서비스를 제공합니다.</p>
<ul>
<li>디지털 명함 생성, 저장, 조회, 수정, 삭제</li>
<li>명함 앞면/뒷면 디자인 및 캔버스 편집</li>
<li>명함 이미지 저장 및 공유</li>
<li>전자서명 생성, 저장, 수정, 삭제</li>
<li>광고 기반 무료 이용 환경 제공</li>
</ul>

<h2>제3조 (이용 조건)</h2>
<ul>
<li>앱은 별도의 회원가입 없이 사용할 수 있습니다.</li>
<li>일부 기능은 네트워크 통신, 파일 업로드 또는 외부 저장소 접근을 포함할 수 있습니다.</li>
<li>앱 기능과 제공 방식은 업데이트에 따라 변경될 수 있습니다.</li>
</ul>

<h2>제4조 (이용자의 의무)</h2>
<ul>
<li>이용자는 본인 책임 하에 명함 및 전자서명 정보를 입력하고 관리해야 합니다.</li>
<li>타인의 권리를 침해하거나 불법적인 내용으로 앱을 이용해서는 안 됩니다.</li>
<li>앱의 정상적인 운영을 방해하거나 비정상적인 방법으로 접근해서는 안 됩니다.</li>
</ul>

<h2>제5조 (데이터 및 저장 파일)</h2>
<ul>
<li>이용자가 입력한 명함 정보, 디자인 정보, 전자서명 정보, 업로드 파일은 서비스 제공을 위해 저장될 수 있습니다.</li>
<li>이용자는 필요한 데이터를 스스로 관리해야 하며, 삭제 전 별도 보관 여부를 확인해야 합니다.</li>
<li>삭제된 데이터는 시스템 반영 과정에서 순차적으로 제거될 수 있습니다.</li>
</ul>

<h2>제6조 (광고 및 외부 서비스)</h2>
<ul>
<li>앱은 Google AdMob 등 외부 서비스를 활용해 광고를 제공할 수 있습니다.</li>
<li>광고 및 외부 인프라 사용과 관련된 사항은 각 제공업체의 정책을 따를 수 있습니다.</li>
</ul>

<h2>제7조 (지식재산권)</h2>
<ul>
<li>앱, 로고, UI, 서비스 구성에 대한 권리는 회사에 귀속됩니다.</li>
<li>이용자가 직접 작성하거나 업로드한 명함 내용과 전자서명 이미지에 대한 책임은 이용자에게 있습니다.</li>
</ul>

<h2>제8조 (면책)</h2>
<ul>
<li>회사는 무료 서비스 제공 과정에서 발생한 일반적 장애 또는 중단에 대해 고의 또는 중대한 과실이 없는 한 책임지지 않습니다.</li>
<li>기기 변경, 앱 삭제, 이용자 실수, 제3자 공유 등으로 발생한 데이터 손실에 대해 회사는 책임지지 않습니다.</li>
<li>앱에 저장된 명함 또는 전자서명 정보의 정확성, 적법성, 대외적 효력은 이용자가 직접 확인해야 합니다.</li>
</ul>

<h2>제9조 (약관 변경)</h2>
<p>회사는 서비스 변경 또는 관련 법령 변경에 따라 본 약관을 수정할 수 있으며, 중요한 변경 사항은 앱 또는 관련 페이지를 통해 안내합니다.</p>

<h2>제10조 (문의)</h2>
<ul>
<li><strong>상호:</strong> BroSister</li>
<li><strong>이메일:</strong> admin@officialsite.kr</li>
<li><strong>웹사이트:</strong> brosister.officialsite.kr</li>
</ul>
""".strip()


def terms_en() -> str:
    return """
<h1>Named Terms of Service</h1>

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

<h2>1. Purpose</h2>
<p>These Terms govern the conditions of use, procedures, and the rights and obligations between BroSister (the "Company") and users of the Named app service.</p>

<h2>2. Services</h2>
<p>The Company provides the following services:</p>
<ul>
<li>Creating, saving, viewing, editing, and deleting digital business cards</li>
<li>Front/back card design and canvas editing</li>
<li>Saving and sharing card images</li>
<li>Creating, saving, editing, and deleting electronic signatures</li>
<li>Providing a free ad-supported usage environment</li>
</ul>

<h2>3. Conditions of Use</h2>
<ul>
<li>The app may be used without separate account registration.</li>
<li>Some features may involve network communication, file uploads, or access to external storage.</li>
<li>App features and delivery methods may change through updates.</li>
</ul>

<h2>4. User Obligations</h2>
<ul>
<li>Users are responsible for entering and managing their own business card and signature information.</li>
<li>Users must not use the app in a way that infringes the rights of others or involves unlawful content.</li>
<li>Users must not interfere with normal operation or attempt abnormal access.</li>
</ul>

<h2>5. Data and Stored Files</h2>
<ul>
<li>Business card information, design data, signature data, and uploaded files may be stored to provide the service.</li>
<li>Users are responsible for managing any data they need and should confirm whether to back it up before deletion.</li>
<li>Deleted data may be removed from the system in sequence during backend processing.</li>
</ul>

<h2>6. Advertising and External Services</h2>
<ul>
<li>The app may use external services such as Google AdMob to provide advertising.</li>
<li>Matters related to advertising and external infrastructure may be subject to the policies of those providers.</li>
</ul>

<h2>7. Intellectual Property</h2>
<ul>
<li>Rights to the app, logo, UI, and service composition belong to the Company.</li>
<li>Users remain responsible for the business card content and signature images they create or upload.</li>
</ul>

<h2>8. Disclaimer</h2>
<ul>
<li>The Company is not liable for ordinary interruptions or failures in the free service unless caused by willful misconduct or gross negligence.</li>
<li>The Company is not responsible for data loss caused by device changes, app deletion, user mistakes, or third-party sharing.</li>
<li>Users must independently verify the accuracy, legality, and external effect of business card and signature information stored in the app.</li>
</ul>

<h2>9. Changes to These Terms</h2>
<p>The Company may revise these Terms due to service changes or applicable law, and material changes will be announced through the app or related pages.</p>

<h2>10. Contact</h2>
<ul>
<li><strong>Company:</strong> BroSister</li>
<li><strong>Email:</strong> admin@officialsite.kr</li>
<li><strong>Website:</strong> brosister.officialsite.kr</li>
</ul>
""".strip()


def load_all_env():
    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))
    return {**os.environ, **loaded_env}


def upsert_setting(cursor):
    url = 'https://app-master.officialsite.kr/privacy/named?type=terms'
    cursor.execute("SELECT id FROM app_settings WHERE app_name = %s AND setting_key = 'terms_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, 'terms_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='terms' 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, 'terms', %s, %s, %s, '1.0', '2026-04-21')",
            ('named', language_code, title, content),
        )


def main():
    env = load_all_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 이용약관', terms_ko())
    upsert_policy(cursor, 'en', 'Named Terms of Service', terms_en())
    conn.commit()
    cursor.close()
    conn.close()
    print('Named terms URL/policy synced successfully.')


if __name__ == '__main__':
    main()
