import sqlite3

conn = sqlite3.connect('backend/sale.db')
cursor = conn.cursor()

cursor.execute("SELECT id, name FROM categories")
categories = cursor.fetchall()

print(f"Found {len(categories)} categories")

brand_keywords = [
    'MEVIUS', 'Camel', 'Marlboro', 'Lucky', 'Kent', 'Seven Stars', 'Winston',
    'Lark', 'Pianissimo', 'Caster', 'Hope', 'Peace', 'Cabin', 'Golden Bat',
    'Black Spider', 'Che', 'Ark Royal', 'Cigaronne', 'TEREA', 'IQOS', 'HEETS',
    'Fiit', 'neo', 'sentia', 'virto', 'BON', 'LEAF', 'glow', 'Ploom',
    'American Spirit', 'Pall Mall', 'Davidoff', 'Dunhill', 'Parliament',
    'Virginia', 'Mild Seven', 'Salem', 'Kool', 'Newport', 'Carlton',
    'Merit', 'Vantage', 'Now', 'Tareyton', 'Belair', 'L&M',
    'Bond', 'Vogue', 'Rothmans', 'Gauloises', 'Gitanes', 'Prince',
    'メビウス', 'キャメル', 'マールボロ', 'ラッキー', 'ケント', 'セブンスター', 'ウィンストン',
    'ピアニッシモ', 'キャスター', 'ホープ', 'ピース', 'キャビン', 'ゴールデンバット',
    'ブラック', 'チェ', 'アーク', 'シガローネ', 'テリア', 'アイコス', 'ヒーツ',
    'フィット', 'ネオ', 'センシア', 'ヴェルト', 'ボン', 'リーフ', 'グロー', 'プルーム',
    'アメリカンスピリット', 'パーラメント', 'バージニア', 'マイルドセブン', 'セーラム', 'クール',
    'ラーク', 'ホープ', 'ピース', 'キャビン', 'キャメル', 'マールボロ'
]

migrated_count = 0
for cat_id, cat_name in categories:
    is_brand = False
    for keyword in brand_keywords:
        if keyword.lower() in cat_name.lower():
            is_brand = True
            break
    
    if is_brand:
        cursor.execute("SELECT id FROM brands WHERE name = ?", (cat_name,))
        existing = cursor.fetchone()
        if existing:
            brand_id = existing[0]
        else:
            cursor.execute("INSERT INTO brands (name, created_at, updated_at) VALUES (?, datetime('now'), datetime('now'))", (cat_name,))
            brand_id = cursor.lastrowid
        
        cursor.execute("UPDATE products SET brand_id = ? WHERE id IN (SELECT product_id FROM product_categories WHERE category_id = ?)", (brand_id, cat_id))
        cursor.execute("DELETE FROM product_categories WHERE category_id = ?", (cat_id,))
        cursor.execute("DELETE FROM categories WHERE id = ?", (cat_id,))
        migrated_count += 1
        print(f"Migrated brand: {cat_name}")

print(f"\nMigrated {migrated_count} brands")

new_categories = [
    ('卷烟', '传统卷烟产品'),
    ('IQOS烟弹', 'IQOS专用加热烟弹'),
    ('手卷烟丝', '手卷烟丝和烟纸'),
    ('雪茄', '雪茄产品'),
    ('电子烟', '电子烟及相关产品'),
    ('薄荷烟', '薄荷口味卷烟'),
    ('超细烟', '超细支卷烟'),
]

for name, desc in new_categories:
    cursor.execute("SELECT id FROM categories WHERE name = ?", (name,))
    if not cursor.fetchone():
        cursor.execute("INSERT INTO categories (name, description, created_at, updated_at) VALUES (?, ?, datetime('now'), datetime('now'))", (name, desc))
        print(f"Created category: {name}")

conn.commit()
conn.close()

print("\nMigration completed!")
