import os
import pymysql


def load_env(env_path):
    if not os.path.exists(env_path):
        return {}
    env = {}
    with open(env_path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            key, value = line.split("=", 1)
            env[key.strip()] = value.strip().strip('"').strip("'")
    return env


base_dir = os.path.dirname(os.path.abspath(__file__))
env_file = os.path.join(base_dir, "..", ".env")
env = load_env(env_file)

db_host = os.getenv("DB_HOST", env.get("DB_HOST", "localhost"))
db_user = os.getenv("DB_USER", env.get("DB_USER", "root"))
db_password = os.getenv("DB_PASSWORD", env.get("DB_PASSWORD", ""))
db_port = int(os.getenv("DB_PORT", env.get("DB_PORT", "3306")))
db_name = os.getenv("DB_NAME", env.get("DB_NAME", "app_master"))

conn = pymysql.connect(
    host=db_host,
    port=db_port,
    user=db_user,
    password=db_password,
    database=db_name,
    charset="utf8mb4",
)
cursor = conn.cursor(pymysql.cursors.DictCursor)


def seed_privacy_policy():
    effective_date = "2026-03-11"

    cursor.execute(
        """
        SELECT id FROM app_policies
        WHERE app_name = %s AND policy_type = 'privacy' AND language_code = 'ko'
        LIMIT 1
        """,
        ("kaomoji",),
    )
    has_ko = cursor.fetchone() is not None

    cursor.execute(
        """
        SELECT id FROM app_policies
        WHERE app_name = %s AND policy_type = 'privacy' AND language_code = 'en'
        LIMIT 1
        """,
        ("kaomoji",),
    )
    has_en = cursor.fetchone() is not None

    if has_ko and has_en:
        print("Kaomoji privacy policy already exists. Updating.")

    content_ko = f"""
<h1>카오모지 개인정보 처리방침</h1>

<div class="highlight">
<strong>시행일자:</strong> 2026년 03월 11일<br>
<strong>최종 수정일:</strong> 2026년 03월 11일
</div>

<h2>1. 개인정보의 처리 목적</h2>
<p>카오모지(이하 "회사")은 다음 목적을 위해 개인정보를 처리합니다.</p>
<ul>
  <li>카오모지 목록 제공 및 복사 기능 제공</li>
  <li>즐겨찾기 저장/관리 기능 제공</li>
  <li>서비스 품질 개선을 위한 이용 통계(복사 횟수) 관리</li>
</ul>

<h2>2. 수집하는 개인정보 항목</h2>
<p>카오모지는 회원가입을 요구하지 않습니다.</p>

<h3>2-1. 필수 수집 항목</h3>
<ul>
  <li>없음</li>
</ul>

<h3>2-2. 자동 수집 항목</h3>
<ul>
  <li>없음</li>
</ul>

<h2>3. 개인정보의 보유 및 이용 기간</h2>
<ul>
  <li>즐겨찾기 및 복사 횟수 등 앱 내 저장 정보는 사용자 기기에만 로컬 저장됩니다.</li>
  <li>앱 삭제 시 로컬 데이터는 함께 삭제됩니다.</li>
</ul>

<h2>4. 개인정보의 제3자 제공</h2>
<p>회사는 이용자의 개인정보를 외부에 제공하지 않습니다. 단, 광고 제공을 위해 Google AdMob을 사용할 수 있으며, 이 경우 Google의 개인정보 처리방침이 적용됩니다.</p>

<h2>4-1. 광고 서비스</h2>
<ul>
  <li><strong>광고 플랫폼:</strong> Google AdMob</li>
  <li><strong>광고 유형:</strong> 배너 광고, 전면 광고</li>
  <li><strong>처리 정보:</strong> 광고 식별자, 광고 성과 측정 정보 등 (Google 정책에 따름)</li>
  <li><strong>관련 정책:</strong> <a href="https://policies.google.com/privacy" target="_blank">Google 개인정보 처리방침</a></li>
</ul>

<h2>5. 개인정보 처리 위탁</h2>
<p>회사는 개인정보 처리 업무를 외부에 위탁하지 않습니다.</p>

<h2>6. 이용자의 권리와 행사 방법</h2>
<ul>
  <li>이용자는 앱 삭제를 통해 로컬 저장 데이터를 삭제할 수 있습니다.</li>
</ul>

<h2>7. 개인정보 보호책임자</h2>
<p>개인정보 관련 문의는 아래로 연락주시기 바랍니다.</p>
<ul>
  <li><strong>책임자명:</strong> 이상현</li>
  <li><strong>이메일:</strong> admin@officialsite.kr</li>
  <li><strong>담당부서:</strong> 고객지원팀</li>
</ul>

<h2>8. 고지의 의무</h2>
<p>본 개인정보 처리방침은 법령·정책 또는 보안기술의 변경에 따라 내용의 추가·삭제 및 수정이 있을 때에는 변경되는 개인정보 처리방침을 시행하기 최소 7일 전에 앱 또는 홈페이지를 통해 고지하겠습니다.</p>
"""

    content_en = f"""
<h1>Kaomoji Privacy Policy</h1>

<div class="highlight">
<strong>Effective Date:</strong> March 11, 2026<br>
<strong>Last Updated:</strong> March 11, 2026
</div>

<h2>1. Purpose of Processing Personal Information</h2>
<p>Kaomoji (the "Company") processes personal information for the following purposes:</p>
<ul>
  <li>Providing kaomoji lists and copy functionality</li>
  <li>Providing favorites save/manage functionality</li>
  <li>Managing usage statistics (copy counts) for service quality improvement</li>
</ul>

<h2>2. Items of Personal Information Collected</h2>
<p>Kaomoji does not require sign-up.</p>

<h3>2-1. Required Items</h3>
<ul>
  <li>None</li>
</ul>

<h3>2-2. Automatically Collected Items</h3>
<ul>
  <li>None</li>
</ul>

<h2>3. Retention and Use Period</h2>
<ul>
  <li>Favorites and copy counts are stored locally on the user's device only.</li>
  <li>Local data is deleted when the app is uninstalled.</li>
</ul>

<h2>4. Provision to Third Parties</h2>
<p>The Company does not provide personal information to third parties. However, Google AdMob may be used for advertising, and Google's privacy policy applies.</p>

<h2>4-1. Advertising Services</h2>
<ul>
  <li><strong>Platform:</strong> Google AdMob</li>
  <li><strong>Ad Types:</strong> Banner Ads, Interstitial Ads</li>
  <li><strong>Data Processed:</strong> Advertising identifiers and performance data (subject to Google's policies)</li>
  <li><strong>Policy:</strong> <a href="https://policies.google.com/privacy" target="_blank">Google Privacy Policy</a></li>
</ul>

<h2>5. Outsourcing of Processing</h2>
<p>The Company does not outsource the processing of personal information.</p>

<h2>6. User Rights and How to Exercise Them</h2>
<ul>
  <li>Users can delete local data by uninstalling the app.</li>
</ul>

<h2>7. Person in Charge of Personal Information Protection</h2>
<p>For privacy-related inquiries, please contact:</p>
<ul>
  <li><strong>Name:</strong> Sanghyun Lee</li>
  <li><strong>Email:</strong> admin@officialsite.kr</li>
  <li><strong>Department:</strong> Customer Support Team</li>
</ul>

<h2>8. Notice of Changes</h2>
<p>This privacy policy may be updated due to changes in laws, policies, or security technologies. Any changes will be announced through the app or website at least 7 days before implementation.</p>
"""

    if not has_ko:
        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)
            """,
            (
                "kaomoji",
                "privacy",
                "ko",
                "카오모지 개인정보 처리방침",
                content_ko,
                "1.0.1",
                effective_date,
            ),
        )
        print("Kaomoji privacy policy inserted (ko).")
    else:
        cursor.execute(
            """
            UPDATE app_policies
               SET content = %s, version = %s, effective_date = %s
             WHERE app_name = 'kaomoji' AND policy_type = 'privacy' AND language_code = 'ko'
            """,
            (content_ko, "1.0.1", effective_date),
        )
        print("Kaomoji privacy policy updated (ko).")

    if not has_en:
        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)
            """,
            (
                "kaomoji",
                "privacy",
                "en",
                "Kaomoji Privacy Policy",
                content_en,
                "1.0.1",
                effective_date,
            ),
        )
        print("Kaomoji privacy policy inserted (en).")
    else:
        cursor.execute(
            """
            UPDATE app_policies
               SET content = %s, version = %s, effective_date = %s
             WHERE app_name = 'kaomoji' AND policy_type = 'privacy' AND language_code = 'en'
            """,
            (content_en, "1.0.1", effective_date),
        )
        print("Kaomoji privacy policy updated (en).")


def main():
    seed_privacy_policy()
    conn.commit()
    print("Done.")


if __name__ == "__main__":
    try:
        main()
    finally:
        cursor.close()
        conn.close()
