#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
크로마키 스크린 앱 데이터베이스 설정 스크립트
- 개인정보처리방침 추가
- 앱 설정 테이블 추가
- 인앱 구매 테이블 추가
"""

import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

import pymysql
from datetime import datetime

# 데이터베이스 연결 정보
DB_CONFIG = {
    'host': 'officialsite.kr',
    'user': 'admin',
    'password': 'dlgks~123',
    'port': 23306,
    'database': 'app_master',
    'charset': 'utf8mb4'
}

# 크로마키 개인정보처리방침 (한국어)
CHROMAKEY_PRIVACY_KO = """
<h1>크로마키 스크린 개인정보 처리방침</h1>

<div class="highlight">
<strong>시행일자:</strong> 2025년 1월 30일<br>
<strong>최종 수정일:</strong> 2025년 1월 30일
</div>

<h2>1. 개인정보의 처리목적</h2>
<p>크로마키 스크린('크로마키 스크린' 또는 '회사')은 다음의 목적을 위하여 개인정보를 처리합니다.</p>
<ul>
<li>크로마키 배경 화면 제공 서비스</li>
<li>앱 사용 통계 분석 및 서비스 개선</li>
<li>Google AdMob을 통한 광고 제공</li>
</ul>

<h2>2. 수집하는 개인정보 항목</h2>
<p><strong>크로마키 스크린은 사용자의 개인정보를 수집하지 않습니다.</strong></p>
<p>본 앱은 오프라인으로 동작하며, 사용자 데이터는 기기에만 저장됩니다.</p>

<h3>2-1. 로컬 저장 데이터 (기기 내부에만 저장)</h3>
<ul>
<li><strong>앱 설정 데이터:</strong> 선택한 색상, 밝기 설정</li>
<li><strong>사용 횟수 데이터:</strong> 일일 무료 사용 횟수 (날짜, 사용 횟수)</li>
</ul>

<h3>2-2. 자동 수집 항목 (광고 목적)</h3>
<ul>
<li><strong>광고 식별자:</strong> Google AdMob 광고 ID (GAID/IDFA)</li>
<li><strong>기기 정보:</strong> 기기 유형, 운영체제 버전 (광고 최적화 목적)</li>
</ul>

<h2>3. 개인정보의 처리 및 보유기간</h2>
<ul>
<li><strong>로컬 저장 데이터:</strong> 앱 삭제 시 자동 삭제</li>
<li><strong>광고 관련 데이터:</strong> Google AdMob 정책에 따름</li>
</ul>

<h2>4. 개인정보의 제3자 제공</h2>
<p>회사는 사용자의 개인정보를 수집하지 않으므로 제3자에게 제공하지 않습니다. 다만, 아래의 업체가 광고 목적으로 자동으로 정보를 수집할 수 있습니다:</p>
<ul>
<li><strong>Google LLC (AdMob):</strong> 맞춤형 광고 제공 목적</li>
<li>제공 정보: 광고 식별자, 기기 정보, 광고 상호작용 정보</li>
<li>제공 목적: 맞춤형 광고 제공</li>
<li>보유 기간: Google AdMob 정책에 따름</li>
</ul>

<h2>5. 개인정보 처리 위탁</h2>
<table border="1">
<tr><th>수탁업체</th><th>위탁업무</th><th>개인정보 보유기간</th></tr>
<tr><td>Google LLC (AdMob)</td><td>광고 서비스 제공</td><td>AdMob 정책에 따름</td></tr>
</table>

<h2>6. 이용자의 권리</h2>
<p>이용자는 언제든지 다음과 같은 권리를 행사할 수 있습니다:</p>
<ul>
<li><strong>데이터 삭제:</strong> 앱 삭제 시 모든 로컬 데이터가 자동으로 삭제됩니다</li>
<li><strong>광고 ID 재설정:</strong> 기기 설정에서 광고 ID를 재설정하거나 맞춤형 광고를 비활성화할 수 있습니다</li>
</ul>

<h2>7. 개인정보의 안전성 확보조치</h2>
<ul>
<li>모든 데이터는 사용자 기기 내에만 저장됩니다 (외부 전송 없음)</li>
<li>Android SharedPreferences를 이용한 안전한 로컬 저장</li>
<li>회사 서버에 개인정보 저장 또는 전송하지 않음</li>
<li>정기적인 앱 보안 업데이트</li>
</ul>

<h2>8. 개인정보의 파기</h2>
<ul>
<li><strong>자동 파기:</strong> 앱 삭제 시 기기에 저장된 모든 데이터가 자동으로 삭제됩니다</li>
</ul>

<h2>9. 개인정보 보호책임자</h2>
<ul>
<li><strong>담당 부서:</strong> 개발팀</li>
<li><strong>연락처:</strong> admin@officialsite.kr</li>
<li><strong>업무:</strong> 개인정보 처리방침 관련 문의 및 불만 처리</li>
</ul>

<h2>10. 권익침해 구제방법</h2>
<p>개인정보 침해에 대한 신고나 상담은 아래 기관에 문의하실 수 있습니다:</p>
<ul>
<li>개인정보침해신고센터: 118 (privacy.kisa.or.kr)</li>
<li>개인정보분쟁조정위원회: 1833-6972 (www.kopico.go.kr)</li>
<li>대검찰청 사이버범죄수사단: 1301 (www.spo.go.kr)</li>
<li>경찰청 사이버안전국: 182 (cyberbureau.police.go.kr)</li>
</ul>

<h2>11. 고지 의무</h2>
<p>법령, 정책 또는 보안기술의 변경에 따라 개인정보 처리방침이 추가, 삭제 또는 변경될 경우, 시행 최소 7일 전에 앱 업데이트 또는 공지사항을 통해 사용자에게 알립니다.</p>

<h2>12. 기타 정보</h2>
<p><strong>크로마키 스크린은 오프라인 크로마키 배경 앱입니다.</strong> 모든 기능은 인터넷 연결 없이 작동하며, 사용자 데이터는 기기 외부로 전송되지 않습니다. 인터넷 권한은 Google AdMob 광고 표시 목적으로만 사용됩니다.</p>
"""

# 크로마키 개인정보처리방침 (영어)
CHROMAKEY_PRIVACY_EN = """
<h1>Chromakey Screen Privacy Policy</h1>

<div class="highlight">
<strong>Effective Date:</strong> January 30, 2025<br>
<strong>Last Modified:</strong> January 30, 2025
</div>

<h2>1. Purpose of Processing Personal Information</h2>
<p>Chromakey Screen ('Chromakey Screen' or 'Company') processes personal information for the following purposes:</p>
<ul>
<li>Providing chromakey background screen service</li>
<li>App usage statistics analysis and service improvement</li>
<li>Providing advertisements through Google AdMob</li>
</ul>

<h2>2. Personal Information Collected</h2>
<p><strong>Chromakey Screen does not collect user personal information.</strong></p>
<p>This app operates offline, and user data is stored only on the device.</p>

<h3>2-1. Locally Stored Data (stored only on device)</h3>
<ul>
<li><strong>App Settings:</strong> Selected color, brightness settings</li>
<li><strong>Usage Count Data:</strong> Daily free usage count (date, usage count)</li>
</ul>

<h3>2-2. Automatically Collected Items (for advertising purposes)</h3>
<ul>
<li><strong>Advertising Identifier:</strong> Google AdMob advertising ID (GAID/IDFA)</li>
<li><strong>Device Information:</strong> Device type, OS version (for ad optimization)</li>
</ul>

<h2>3. Processing and Retention Period</h2>
<ul>
<li><strong>Locally Stored Data:</strong> Automatically deleted when app is uninstalled</li>
<li><strong>Advertising-related Data:</strong> According to Google AdMob policies</li>
</ul>

<h2>4. Third-Party Sharing</h2>
<p>The company does not collect users' personal information and therefore does not provide it to third parties. However, the following entity may automatically collect information for advertising purposes:</p>
<ul>
<li><strong>Google LLC (AdMob):</strong> For personalized advertising</li>
<li>Information Provided: Advertising identifier, device information, ad interaction information</li>
<li>Purpose: Providing personalized advertising</li>
<li>Retention Period: According to Google AdMob policies</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 LLC (AdMob)</td><td>Advertising Services</td><td>Per AdMob Policy</td></tr>
</table>

<h2>6. User Rights</h2>
<p>Users can exercise the following rights at any time:</p>
<ul>
<li><strong>Data Deletion:</strong> All local data is automatically deleted when the app is uninstalled</li>
<li><strong>Ad ID Reset:</strong> Users can reset advertising ID or opt out of personalized advertising in device settings</li>
</ul>

<h2>7. Security Measures</h2>
<ul>
<li>All data is stored only within user device (no external transmission)</li>
<li>Secure local storage using Android SharedPreferences</li>
<li>No storage or transmission of personal information to company servers</li>
<li>Regular app security updates</li>
</ul>

<h2>8. Data Destruction</h2>
<ul>
<li><strong>Automatic Destruction:</strong> All data stored on device is automatically deleted when app is uninstalled</li>
</ul>

<h2>9. Privacy Officer</h2>
<ul>
<li><strong>Department:</strong> Development Team</li>
<li><strong>Contact:</strong> admin@officialsite.kr</li>
<li><strong>Responsibilities:</strong> Handling inquiries and complaints related to privacy policy</li>
</ul>

<h2>10. Remedy for Rights Infringement</h2>
<p>For reports or counseling regarding personal information infringement, please contact the following organizations:</p>
<ul>
<li>Personal Information Infringement Report Center: 118 (privacy.kisa.or.kr)</li>
<li>Personal Information Dispute Mediation Committee: 1833-6972 (www.kopico.go.kr)</li>
<li>Supreme Prosecutors' Office Cybercrime Investigation Division: 1301 (www.spo.go.kr)</li>
<li>National Police Agency Cyber Safety Bureau: 182 (cyberbureau.police.go.kr)</li>
</ul>

<h2>11. Notification Obligations</h2>
<p>If there are additions, deletions, or modifications to this privacy policy due to changes in laws, policies, or security technologies, we will notify users at least 7 days before implementation through app updates or notices.</p>

<h2>12. Other Information</h2>
<p><strong>Chromakey Screen is an offline chromakey background app.</strong> All functions work without internet connection, and user data is not transmitted outside the device. Internet permission is used only for displaying Google AdMob advertisements.</p>
"""


def setup_chromakey_tables():
    """크로마키 앱 관련 테이블 및 데이터 설정"""
    conn = pymysql.connect(**DB_CONFIG)
    cursor = conn.cursor()

    try:
        # 1. 크로마키 앱 설정 테이블 생성
        print("Creating chromakey_settings table...")
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS chromakey_settings (
                id INT AUTO_INCREMENT PRIMARY KEY,
                setting_key VARCHAR(100) NOT NULL UNIQUE,
                setting_value TEXT,
                description VARCHAR(255),
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """)
        print("[OK] chromakey_settings table created")

        # 2. 크로마키 인앱 구매 테이블 생성
        print("Creating chromakey_purchases table...")
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS chromakey_purchases (
                id INT AUTO_INCREMENT PRIMARY KEY,
                device_id VARCHAR(255) NOT NULL,
                product_id VARCHAR(100) NOT NULL,
                purchase_token TEXT,
                purchase_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                expiry_time TIMESTAMP NULL,
                is_active BOOLEAN DEFAULT TRUE,
                platform ENUM('android', 'ios') NOT NULL,
                receipt_data TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_device_id (device_id),
                INDEX idx_product_id (product_id),
                INDEX idx_is_active (is_active)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """)
        print("[OK] chromakey_purchases table created")

        # 3. 크로마키 사용 통계 테이블 생성
        print("Creating chromakey_stats table...")
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS chromakey_stats (
                id INT AUTO_INCREMENT PRIMARY KEY,
                stat_date DATE NOT NULL,
                total_sessions INT DEFAULT 0,
                ad_views INT DEFAULT 0,
                ad_clicks INT DEFAULT 0,
                purchases INT DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY unique_date (stat_date)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """)
        print("[OK] chromakey_stats table created")

        # 4. 개인정보처리방침 삽입
        print("Inserting chromakey privacy policies...")

        # 한국어 개인정보처리방침
        cursor.execute("""
            INSERT INTO app_policies
            (app_name, policy_type, language_code, title, content, version, effective_date)
            VALUES (%s, %s, %s, %s, %s, %s, %s)
            ON DUPLICATE KEY UPDATE
            content = VALUES(content),
            version = VALUES(version),
            effective_date = VALUES(effective_date),
            updated_at = CURRENT_TIMESTAMP
        """, (
            'chromakey',
            'privacy',
            'ko',
            '크로마키 스크린 개인정보 처리방침',
            CHROMAKEY_PRIVACY_KO,
            '1.0',
            '2025-01-30'
        ))
        print("[OK] Korean privacy policy inserted")

        # 영어 개인정보처리방침
        cursor.execute("""
            INSERT INTO app_policies
            (app_name, policy_type, language_code, title, content, version, effective_date)
            VALUES (%s, %s, %s, %s, %s, %s, %s)
            ON DUPLICATE KEY UPDATE
            content = VALUES(content),
            version = VALUES(version),
            effective_date = VALUES(effective_date),
            updated_at = CURRENT_TIMESTAMP
        """, (
            'chromakey',
            'privacy',
            'en',
            'Chromakey Screen Privacy Policy',
            CHROMAKEY_PRIVACY_EN,
            '1.0',
            '2025-01-30'
        ))
        print("[OK] English privacy policy inserted")

        # 5. 기본 설정 추가
        print("Inserting default settings...")
        default_settings = [
            ('free_daily_limit', '3', '일일 무료 사용 횟수'),
            ('ad_reward_uses', '1', '광고 시청 시 추가 사용 횟수'),
            ('banner_ad_enabled', 'true', '배너 광고 활성화 여부'),
            ('rewarded_ad_enabled', 'true', '보상형 광고 활성화 여부'),
        ]

        for key, value, desc in default_settings:
            cursor.execute("""
                INSERT INTO chromakey_settings (setting_key, setting_value, description)
                VALUES (%s, %s, %s)
                ON DUPLICATE KEY UPDATE
                setting_value = VALUES(setting_value),
                description = VALUES(description)
            """, (key, value, desc))
        print("[OK] Default settings inserted")

        conn.commit()
        print("\n[OK] All chromakey tables and data setup completed!")
        print(f"\n[INFO] Privacy Policy URL: https://app-master.officialsite.kr/privacy/chromakey")
        print(f"[INFO] Privacy Policy URL (English): https://app-master.officialsite.kr/privacy/chromakey?lang=en")

    except Exception as e:
        conn.rollback()
        print(f"[ERROR] Error: {e}")
        raise
    finally:
        cursor.close()
        conn.close()


if __name__ == '__main__':
    setup_chromakey_tables()
