import os
import random
import uuid
import pymysql
import time


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",
)
conn.autocommit(True)
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SET SESSION innodb_lock_wait_timeout = 5")

random.seed(20260311)


def normalize_tag(tag):
    tag = tag.strip()
    if not tag:
        return ""
    return tag if tag.startswith("#") else f"#{tag}"


def build_hashtag_set(kr_pool, en_pool, total_count):
    kr_count = min(len(kr_pool), max(6, total_count - 6))
    en_count = min(len(en_pool), total_count - kr_count)
    if en_count < 2 and len(en_pool) >= 2:
        en_count = 2
        kr_count = min(len(kr_pool), total_count - en_count)

    chosen = []
    if kr_pool:
        chosen.extend(random.sample(kr_pool, k=kr_count))
    if en_pool:
        chosen.extend(random.sample(en_pool, k=en_count))

    unique = []
    seen = set()
    for tag in chosen:
        norm = normalize_tag(tag)
        if norm and norm not in seen:
            unique.append(norm)
            seen.add(norm)

    while len(unique) < total_count and kr_pool:
        candidate = normalize_tag(random.choice(kr_pool))
        if candidate and candidate not in seen:
            unique.append(candidate)
            seen.add(candidate)
    while len(unique) < total_count and en_pool:
        candidate = normalize_tag(random.choice(en_pool))
        if candidate and candidate not in seen:
            unique.append(candidate)
            seen.add(candidate)

    return " ".join(unique), len(unique)


def ensure_category(category):
    cursor.execute(
        "SELECT id FROM tag_shuttle_categories WHERE slug = %s LIMIT 1",
        (category["slug"],),
    )
    row = cursor.fetchone()
    if row:
        return row["id"]

    category_id = str(uuid.uuid4())
    cursor.execute(
        """
        INSERT INTO tag_shuttle_categories (id, name, slug, icon, sort_order, is_active)
        VALUES (%s, %s, %s, %s, %s, TRUE)
        ON DUPLICATE KEY UPDATE
          name = VALUES(name),
          icon = VALUES(icon),
          sort_order = VALUES(sort_order),
          is_active = TRUE
        """,
        (
            category_id,
            category["name"],
            category["slug"],
            category["icon"],
            category["sort_order"],
        ),
    )
    cursor.execute(
        "SELECT id FROM tag_shuttle_categories WHERE slug = %s LIMIT 1",
        (category["slug"],),
    )
    row = cursor.fetchone()
    return row["id"] if row else category_id


def get_existing_titles(category_id):
    cursor.execute(
        "SELECT title FROM tag_shuttle_tags WHERE category_id = %s",
        (category_id,),
    )
    return {row["title"] for row in cursor.fetchall()}


def get_next_sort_order(category_id):
    cursor.execute(
        "SELECT COALESCE(MAX(sort_order), 0) as max_order FROM tag_shuttle_tags WHERE category_id = %s",
        (category_id,),
    )
    return cursor.fetchone()["max_order"] + 1


def seed_bulk():
    set_count = int(os.getenv("TAG_SHUTTLE_SET_COUNT", "30"))
    tag_per_set = int(os.getenv("TAG_SHUTTLE_TAGS_PER_SET", "15"))
    slug_filter_raw = os.getenv("TAG_SHUTTLE_SLUGS", "").strip()
    slug_filter = []
    if slug_filter_raw:
        slug_filter = [s.strip() for s in slug_filter_raw.split(",") if s.strip()]

    categories = [
        {
            "name": "인기/일상",
            "slug": "daily-popular",
            "icon": "🔥",
            "sort_order": 1,
            "titles": ["오늘의 일상", "데일리 감성", "소확행 기록", "일상 소통", "감성 데일리"],
            "kr": [
                "#일상", "#데일리", "#소확행", "#힐링", "#감성", "#감성스타그램", "#카페라이프",
                "#워라밸라이프", "#자기계발", "#취미", "#미니멀리즘", "#홈스타그램", "#혼라이프",
                "#자취방", "#집꾸미기", "#트렌드", "#봄감성", "#리빙스타일", "#라이프스타일",
            ],
            "en": [
                "#instagood", "#instadaily", "#photooftheday", "#picoftheday", "#happy",
                "#love", "#lifestyle", "#instamood", "#sunset", "#cute", "#selfie",
            ],
        },
        {
            "name": "카페/맛집",
            "slug": "cafe-food",
            "icon": "☕",
            "sort_order": 2,
            "titles": ["카페 투어", "맛집 탐방", "디저트 시간", "브런치 무드", "푸드 감성"],
            "kr": [
                "#맛집", "#먹스타그램", "#푸드스타그램", "#맛집추천", "#먹방", "#디저트", "#홈쿡",
                "#요리스타그램", "#집밥", "#브런치", "#야식", "#카페스타그램", "#빵지순례",
                "#푸드트럭", "#건강식", "#신상맛집", "#한식", "#로컬맛집", "#푸드아트",
                "#홈베이킹", "#푸드스타일링", "#트렌드디저트", "#카페추천",
            ],
            "en": [
                "#food", "#foodie", "#healthyfood", "#photo", "#photography", "#instalike",
                "#trending", "#beautiful",
            ],
        },
        {
            "name": "여행",
            "slug": "travel",
            "icon": "✈️",
            "sort_order": 3,
            "titles": ["여행 감성", "국내 여행", "해외 여행", "힐링 트립", "감성 여행기"],
            "kr": [
                "#여행", "#여행스타그램", "#여행에미치다", "#트래블", "#세계여행", "#여행사진",
                "#여행일기", "#여행기록", "#여행중", "#여행지추천", "#여행블로거", "#감성여행",
                "#여행코디", "#여행맛집", "#여행플랜", "#국내여행", "#해외여행", "#여행후기",
                "#휴양지", "#배낭여행", "#핫플여행", "#자연여행", "#캠핑여행", "#로컬여행",
                "#여행그램",
            ],
            "en": [
                "#travel", "#nature", "#traveltips", "#travelessentials", "#airplanemode",
                "#beachaesthetic", "#solotravel", "#luxurytravel",
            ],
        },
        {
            "name": "OOTD/패션",
            "slug": "ootd-fashion",
            "icon": "🧢",
            "sort_order": 4,
            "titles": ["오늘의 코디", "데일리 룩", "스트릿 감성", "미니멀 룩", "패션 무드"],
            "kr": [
                "#패션", "#스타일", "#OOTD", "#데일리룩", "#스트릿패션", "#패션블로거",
                "#패션스타그램", "#패션디자인", "#패션모델", "#패션쇼", "#패션피플",
                "#패션코디", "#패션그램", "#패션아이템", "#패션디자이너", "#패션화보",
                "#패션잡지", "#패션포토", "#봄패션", "#신상룩", "#미니멀룩",
                "#패션스타일링", "#패션브랜드", "#스트릿룩", "#패션쇼핑",
            ],
            "en": [
                "#fashion", "#style", "#ootd", "#outfit", "#fashionstyle",
                "#fashionreels", "#winterfashion", "#stylemepretty",
            ],
        },
        {
            "name": "뷰티/메이크업",
            "slug": "beauty",
            "icon": "💄",
            "sort_order": 5,
            "titles": ["메이크업 룩", "스킨케어 루틴", "뷰티 무드", "오늘의 뷰티", "셀프케어"],
            "kr": [
                "#뷰티", "#메이크업", "#화장품", "#스킨케어", "#뷰티블로거", "#네일아트",
                "#헤어스타일", "#뷰티스타그램", "#코스메틱", "#셀프케어", "#립메이크업",
                "#아이메이크업", "#베이스메이크업", "#클렌징", "#헤어케어", "#피부관리",
                "#네일스타그램", "#향수", "#봄메이크업", "#스킨케어추천", "#페이스케어",
                "#트렌드뷰티", "#컬러메이크업", "#클린뷰티",
            ],
            "en": [
                "#beauty", "#makeup", "#skincare", "#nails", "#nailart",
                "#beautytips", "#trending",
            ],
        },
        {
            "name": "피트니스/헬스",
            "slug": "fitness",
            "icon": "💪",
            "sort_order": 6,
            "titles": ["운동 루틴", "홈트 챌린지", "헬스 기록", "건강 습관", "다이어트 일기"],
            "kr": [
                "#운동", "#피트니스", "#헬스", "#다이어트", "#요가", "#홈트",
                "#운동하는여자", "#운동하는남자", "#건강", "#웨이트트레이닝",
                "#헬스타그램", "#런닝", "#근력운동", "#운동습관", "#홈트레이닝",
                "#몸만들기", "#필라테스", "#근육", "#자기관리", "#홈트추천",
                "#바디챌린지", "#헬스루틴", "#코어운동", "#피트니스챌린지",
                "#건강한습관",
            ],
            "en": [
                "#fitness", "#fitnessjourney", "#homeworkout", "#healthylifestyle",
                "#healthyeating", "#trending",
            ],
        },
        {
            "name": "라이프스타일/감성",
            "slug": "lifestyle",
            "icon": "🕊️",
            "sort_order": 7,
            "titles": ["라이프스타일", "감성 기록", "힐링 라이프", "취미 시간", "일상 무드"],
            "kr": [
                "#라이프스타일", "#일상", "#데일리", "#소확행", "#힐링", "#감성",
                "#인테리어", "#취미", "#자기계발", "#미니멀리즘", "#플랜테리어",
                "#홈스타그램", "#힐링라이프", "#방꾸미기", "#카페라이프", "#리빙스타일",
                "#혼라이프", "#자취방", "#감성스타그램", "#트렌드", "#집꾸미기",
                "#홈카페인테리어", "#디지털디톡스", "#워라밸라이프", "#홈가드닝",
            ],
            "en": [
                "#lifestyle", "#instamood", "#sunset", "#selfie", "#cute", "#happy",
                "#instadaily",
            ],
        },
        {
            "name": "인테리어/홈",
            "slug": "interior",
            "icon": "🏠",
            "sort_order": 8,
            "titles": ["홈 인테리어", "집꾸미기", "홈데코", "감성 공간", "리빙 스타일"],
            "kr": [
                "#인테리어", "#홈데코", "#인테리어디자인", "#셀프인테리어", "#홈스타일링",
                "#가구", "#리모델링", "#플랜테리어", "#인테리어소품", "#조명", "#집꾸미기",
                "#홈스타그램", "#방꾸미기", "#홈카페인테리어",
            ],
            "en": [
                "#bohemianinterior", "#industrialinterior", "#interiorphotography",
                "#homeinteriorsuk", "#hyggelife", "#hyggelifestyle",
            ],
        },
        {
            "name": "공부/자기계발",
            "slug": "study",
            "icon": "📚",
            "sort_order": 9,
            "titles": ["공부 기록", "자기계발 루틴", "독서 습관", "목표 달성", "성장 로그"],
            "kr": [
                "#공부", "#자기계발", "#독서", "#온라인강의", "#외국어공부", "#자격증",
                "#취업준비", "#멘탈케어", "#시간관리", "#목표달성",
            ],
            "en": [
                "#goals", "#motivation", "#productivity", "#growth", "#education",
            ],
        },
        {
            "name": "반려동물",
            "slug": "pet",
            "icon": "🐾",
            "sort_order": 10,
            "titles": ["댕냥이 일상", "반려동물 기록", "귀여움 폭발", "펫스타그램", "산책 타임"],
            "kr": ["#반려동물"],
            "en": [
                "#pets", "#petsofinstagram", "#dog", "#dogsofinstagram", "#instadog",
                "#dogoftheday", "#doglover", "#doglife", "#catsofinstagram",
            ],
        },
        {
            "name": "릴스/트렌딩",
            "slug": "reels",
            "icon": "🎬",
            "sort_order": 11,
            "titles": ["릴스 트렌딩", "바이럴 리얼스", "탐색 탑승", "오늘의 릴스", "트렌드 모음"],
            "kr": ["#트렌드"],
            "en": ["#reels", "#reelsvideo", "#trending", "#fashionreels", "#instagood"],
        },
        {
            "name": "가족/육아",
            "slug": "family",
            "icon": "👶",
            "sort_order": 12,
            "titles": ["가족 시간", "육아 일상", "아이와 함께", "패밀리 모먼트", "성장 기록"],
            "kr": ["#육아"],
            "en": ["#family", "#kids", "#parenting", "#love", "#happy"],
        },
    ]

    for category in categories:
        if slug_filter and category["slug"] not in slug_filter:
            continue
        print(f"Seeding category: {category['name']} ({category['slug']})")
        for attempt in range(3):
            try:
                category_id = ensure_category(category)
                cursor.execute(
                    "SELECT COUNT(*) as cnt FROM tag_shuttle_tags WHERE category_id = %s",
                    (category_id,),
                )
                current_count = cursor.fetchone()["cnt"]
                target_count = current_count + set_count

                existing_titles = get_existing_titles(category_id)
                sort_order = get_next_sort_order(category_id)

                i = 0
                while current_count < target_count:
                    i += 1
                    title = f"{random.choice(category['titles'])} 세트 {i + 1:02d}"
                    if title in existing_titles:
                        continue

                    hashtags, count = build_hashtag_set(
                        category["kr"],
                        category["en"],
                        tag_per_set,
                    )

                    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)
                        """,
                        (
                            str(uuid.uuid4()),
                            category_id,
                            title,
                            hashtags,
                            count,
                            sort_order,
                        ),
                    )
                    existing_titles.add(title)
                    current_count += 1
                    sort_order += 1

                print(f"{category['name']} seeded: +{set_count} sets (total {current_count})")
                break
            except pymysql.err.OperationalError as exc:
                if exc.args and exc.args[0] == 1205 and attempt < 2:
                    wait = 2 + attempt
                    print(f"Lock wait timeout for {category['name']}, retrying in {wait}s...")
                    time.sleep(wait)
                    continue
                raise


def main():
    try:
        seed_bulk()
        print("Tag Shuttle bulk seed done.")
    finally:
        cursor.close()
        conn.close()


if __name__ == "__main__":
    main()
