import os
import re
import uuid
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 create_tables():
    cursor.execute(
        """
        CREATE TABLE IF NOT EXISTS tag_shuttle_categories (
            id VARCHAR(36) PRIMARY KEY,
            name VARCHAR(50) NOT NULL,
            slug VARCHAR(50) NOT NULL UNIQUE,
            icon VARCHAR(20) DEFAULT '#',
            sort_order INT DEFAULT 0,
            is_active BOOLEAN DEFAULT TRUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_active (is_active),
            INDEX idx_sort (sort_order)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """
    )

    cursor.execute(
        """
        CREATE TABLE IF NOT EXISTS tag_shuttle_tags (
            id VARCHAR(36) PRIMARY KEY,
            category_id VARCHAR(36) NOT NULL,
            title VARCHAR(120) NOT NULL,
            hashtags TEXT NOT NULL,
            hashtag_count INT DEFAULT 0,
            copy_count INT DEFAULT 0,
            sort_order INT DEFAULT 0,
            is_active BOOLEAN DEFAULT TRUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_category (category_id),
            INDEX idx_active (is_active),
            CONSTRAINT fk_tag_shuttle_category FOREIGN KEY (category_id)
                REFERENCES tag_shuttle_categories(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """
    )

    cursor.execute(
        """
        CREATE TABLE IF NOT EXISTS tag_shuttle_my_tags (
            id VARCHAR(36) PRIMARY KEY,
            device_id VARCHAR(64) NOT NULL,
            tag_id VARCHAR(36) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            UNIQUE KEY uniq_device_tag (device_id, tag_id),
            INDEX idx_device (device_id),
            CONSTRAINT fk_tag_shuttle_my_tag FOREIGN KEY (tag_id)
                REFERENCES tag_shuttle_tags(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        """
    )


def count_hashtags(text):
    return len([t for t in re.split(r"\s+", text.strip()) if t.startswith("#")])


def seed_data():
    cursor.execute("SELECT COUNT(*) as count FROM tag_shuttle_categories")
    if cursor.fetchone()["count"] > 0:
        print("Tag Shuttle data already exists. Skipping seed.")
        return

    categories = [
        {"name": "인기/일상", "slug": "daily-popular", "icon": "🔥"},
        {"name": "카페/맛집", "slug": "cafe-food", "icon": "☕"},
        {"name": "여행", "slug": "travel", "icon": "✈️"},
        {"name": "OOTD/패션", "slug": "ootd-fashion", "icon": "🧢"},
        {"name": "반려동물", "slug": "pet", "icon": "🐾"},
    ]

    category_ids = {}
    for idx, category in enumerate(categories, start=1):
        cid = str(uuid.uuid4())
        category_ids[category["slug"]] = cid
        cursor.execute(
            """
            INSERT INTO tag_shuttle_categories (id, name, slug, icon, sort_order, is_active)
            VALUES (%s, %s, %s, %s, %s, TRUE)
            """,
            (cid, category["name"], category["slug"], category["icon"], idx),
        )

    tag_sets = [
        {
            "slug": "daily-popular",
            "title": "일상 & 소통 (맞팔/좋반)",
            "hashtags": "#일상 #데일리 #소통 #맞팔 #맞팔환영 #좋아요 #좋아요반사 #좋반 #팔로우 #팔로우미 "
                        "#팔로워 #인친 #인친환영 #일상스타그램 #데일리그램 #오늘의기록 #인스타그램 "
                        "#일상공유 #맞팔그램 #소확행 #작은행복 #감성",
        },
        {
            "slug": "daily-popular",
            "title": "릴스 & 알고리즘 부스터",
            "hashtags": "#릴스 #릴스추천 #인스타릴스 #릴스탐험 #알고리즘 #추천 #인기게시물 "
                        "#트렌드 #바이럴 #인스타그램 #릴탐 #정보 #인사이트 #팔로우늘리기 "
                        "#계정성장 #소통 #해시태그 #영상편집 #콘텐츠",
        },
        {
            "slug": "daily-popular",
            "title": "직장인 & 퇴근 후 일상",
            "hashtags": "#직장인 #직장인일상 #퇴근 #퇴근후 #야근 #월급루팡 #회사생활 #직장인그램 "
                        "#출근 #출근길 #퇴근길 #오피스룩 #회사밥 #회식 #퇴근후일상 #힐링 #혼밥 "
                        "#일상기록 #공감 #직장생활",
        },
        {
            "slug": "cafe-food",
            "title": "카페 투어 & 감성 샷",
            "hashtags": "#카페 #카페투어 #카페그램 #커피 #디저트 #감성카페 #카페스타그램 #라떼 "
                        "#아메리카노 #디저트맛집 #카페사진 #커피스타그램 #주말카페 #카페추천",
        },
        {
            "slug": "cafe-food",
            "title": "맛집 기록 & 먹방",
            "hashtags": "#맛집 #맛집탐방 #먹방 #먹스타그램 #음식사진 #맛집추천 #존맛탱 "
                        "#오늘뭐먹지 #간식 #야식 #맛있는하루 #먹부림",
        },
        {
            "slug": "travel",
            "title": "국내 여행 감성",
            "hashtags": "#여행 #국내여행 #여행스타그램 #주말여행 #힐링여행 #감성여행 #풍경 "
                        "#여행기록 #여행추천 #여행사진 #여행중",
        },
        {
            "slug": "travel",
            "title": "해외 & 휴양지",
            "hashtags": "#해외여행 #여행스타그램 #여행그램 #휴양지 #여행추천 #바다여행 #여행지 "
                        "#여행사진 #트래블 #travel",
        },
        {
            "slug": "ootd-fashion",
            "title": "오늘의 코디 (OOTD)",
            "hashtags": "#ootd #패션 #데일리룩 #코디 #스타일링 #패션스타그램 #오늘의코디 "
                        "#ootdfashion #스트릿패션 #패션그램",
        },
        {
            "slug": "ootd-fashion",
            "title": "쇼핑 & 스타일",
            "hashtags": "#쇼핑 #패션아이템 #스타일 #룩북 #옷스타그램 #패션아이템추천 "
                        "#신상 #코디추천",
        },
        {
            "slug": "pet",
            "title": "반려동물 일상",
            "hashtags": "#반려동물 #강아지 #고양이 #댕댕이 #냥스타그램 #펫스타그램 "
                        "#반려견 #반려묘 #멍스타그램 #냥냥이 #펫",
        },
        {
            "slug": "pet",
            "title": "귀여움 폭발",
            "hashtags": "#귀여움 #심쿵 #힐링 #펫데일리 #댕댕스타그램 #고양이그램 #반려동물사진",
        },
    ]

    for idx, tag in enumerate(tag_sets, start=1):
        tid = str(uuid.uuid4())
        category_id = category_ids[tag["slug"]]
        hashtags = tag["hashtags"]
        cursor.execute(
            """
            INSERT INTO tag_shuttle_tags
                (id, category_id, title, hashtags, hashtag_count, sort_order, is_active)
            VALUES (%s, %s, %s, %s, %s, %s, TRUE)
            """,
            (tid, category_id, tag["title"], hashtags, count_hashtags(hashtags), idx),
        )

    print("Tag Shuttle seed data inserted.")


def seed_privacy_policy():
    effective_date = "2026-03-11"

    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>
<h3>2-1. 필수 수집 항목</h3>
<ul>
  <li><strong>기기 식별자:</strong> 앱 내에서 생성한 익명 식별자(device_id)</li>
  <li><strong>저장 태그 정보:</strong> 사용자가 “내 태그”로 저장한 태그 ID</li>
</ul>

<h3>2-2. 자동 수집 항목</h3>
<ul>
  <li><strong>이용 통계:</strong> 태그 복사 횟수</li>
</ul>

<h2>3. 개인정보의 보유 및 이용 기간</h2>
<ul>
  <li><strong>기기 식별자 및 내 태그 정보:</strong> 사용자가 앱을 삭제하거나 내 태그 삭제 시까지</li>
  <li><strong>이용 통계(복사 수):</strong> 서비스 제공 및 분석 목적 달성 시까지</li>
</ul>

<h2>4. 개인정보의 제3자 제공</h2>
<p>회사는 원칙적으로 이용자의 개인정보를 외부에 제공하지 않습니다. 다만 법령에 의거하여 수사기관의 요청이 있는 경우 제공될 수 있습니다.</p>

<h2>5. 개인정보 처리 위탁</h2>
<p>회사는 개인정보 처리 업무를 외부에 위탁하지 않습니다.</p>

<h2>6. 이용자의 권리와 행사 방법</h2>
<ul>
  <li>사용자는 앱 내에서 “내 태그”를 삭제할 수 있습니다.</li>
  <li>앱 삭제 시 기기 식별자와 관련 저장 정보는 더 이상 수집되지 않습니다.</li>
</ul>

<h2>7. 개인정보 보호책임자</h2>
<p>개인정보 관련 문의는 아래로 연락주시기 바랍니다.</p>
<ul>
  <li><strong>담당부서:</strong> 개발팀</li>
  <li><strong>연락처:</strong> admin@officialsite.kr</li>
</ul>

<h2>8. 고지의 의무</h2>
<p>본 개인정보 처리방침은 법령·정책 또는 보안기술의 변경에 따라 내용의 추가·삭제 및 수정이 있을 때에는 변경되는 개인정보 처리방침을 시행하기 최소 7일 전에 앱 또는 홈페이지를 통해 고지하겠습니다.</p>
"""
    content_en = f"""
<h1>Tag Shuttle 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>Tag Shuttle (the "Company") processes personal information for the following purposes:</p>
<ul>
  <li>Providing hashtag lists and copy 기능</li>
  <li>Providing the "My Tags" save/manage feature</li>
  <li>Managing usage statistics (copy counts) for service improvement</li>
</ul>

<h2>2. Items of Personal Information Collected</h2>
<h3>2-1. Required Items</h3>
<ul>
  <li><strong>Device Identifier:</strong> An anonymous identifier generated within the app (device_id)</li>
  <li><strong>Saved Tag Information:</strong> Tag IDs saved by the user in "My Tags"</li>
</ul>

<h3>2-2. Automatically Collected Items</h3>
<ul>
  <li><strong>Usage Statistics:</strong> Tag copy counts</li>
</ul>

<h2>3. Retention and Use Period</h2>
<ul>
  <li><strong>Device Identifier and My Tags:</strong> Until the user deletes the app or removes saved tags</li>
  <li><strong>Usage Statistics (copy counts):</strong> Until the purpose of service provision and analysis is achieved</li>
</ul>

<h2>4. Provision to Third Parties</h2>
<p>The Company does not provide personal information to third parties unless required by law or government authorities.</p>

<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 saved tags via the app.</li>
  <li>When the app is deleted, the device identifier and related stored data are no longer collected.</li>
</ul>

<h2>7. Person in Charge of Personal Information Protection</h2>
<p>For privacy-related inquiries, please contact:</p>
<ul>
  <li><strong>Department:</strong> Development Team</li>
  <li><strong>Contact:</strong> admin@officialsite.kr</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>
"""

    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
            title = VALUES(title),
            content = VALUES(content),
            version = VALUES(version),
            effective_date = VALUES(effective_date),
            updated_at = CURRENT_TIMESTAMP
        """,
        (
            "tagshuttle",
            "privacy",
            "ko",
            "태그 셔틀 개인정보 처리방침",
            content_ko,
            "1.0.0",
            effective_date,
        ),
    )

    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
            title = VALUES(title),
            content = VALUES(content),
            version = VALUES(version),
            effective_date = VALUES(effective_date),
            updated_at = CURRENT_TIMESTAMP
        """,
        (
            "tagshuttle",
            "privacy",
            "en",
            "Tag Shuttle Privacy Policy",
            content_en,
            "1.0.0",
            effective_date,
        ),
    )

    print("Tag Shuttle privacy policy upserted.")


def main():
    print("Initializing Tag Shuttle tables...")
    create_tables()
    seed_data()
    seed_privacy_policy()
    conn.commit()
    print("Done.")


if __name__ == "__main__":
    try:
        main()
    finally:
        cursor.close()
        conn.close()
