import os
import sys
from app import app, db
from models import Product

def import_veri_csv():
    csv_path = 'veri.csv'
    
    if not os.path.exists(csv_path):
        print(f"HATA: {csv_path} dosyası bulunamadı!")
        return
    
    with app.app_context():
        print(f"'{csv_path}' dosyası okunuyor...")
        
        with open(csv_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        print(f"Toplam {len(lines)} satır bulundu")
        
        count = 0
        updated = 0
        skipped = 0
        
        for i, line in enumerate(lines[1:], 1):
            parts = line.strip().split('|')
            
            if len(parts) < 11:
                print(f"Satır {i}: Yetersiz veri ({len(parts)} sütun) - Atlanıyor")
                skipped += 1
                continue
            
            try:
                csv_id = int(parts[0])
                title = parts[1]
                description = parts[2]
                price = float(parts[3])
                image = parts[4]
                category = parts[5]
                tags = parts[6]
                keywords = parts[7]
                popular = parts[8].lower() == 'true'
                permanentlink = parts[9]
                
                existing = Product.query.filter_by(csv_id=csv_id).first()
                
                if existing:
                    existing.name = title
                    existing.description = description
                    existing.price = price
                    existing.image_url = image
                    existing.category = category
                    existing.tags = tags
                    existing.keywords = keywords
                    existing.popular = popular
                    existing.permanentlink = permanentlink
                    updated += 1
                    if updated % 100 == 0:
                        print(f"  {updated} ürün güncellendi...")
                else:
                    product = Product(
                        csv_id=csv_id,
                        name=title,
                        description=description,
                        price=price,
                        image_url=image,
                        category=category,
                        tags=tags,
                        keywords=keywords,
                        popular=popular,
                        permanentlink=permanentlink,
                        paddle_product_id=f"prod_{csv_id}",
                        github_release_tag=f"product-{csv_id}",
                        file_parts_count=1,
                        active=True
                    )
                    db.session.add(product)
                    count += 1
                    if count % 100 == 0:
                        print(f"  {count} yeni ürün eklendi...")
                
                if (count + updated) % 500 == 0:
                    db.session.commit()
                    print(f"  Veritabanına kaydedildi (Toplam: {count + updated})")
                
            except Exception as e:
                print(f"Satır {i} hata: {str(e)[:100]}")
                skipped += 1
                continue
        
        db.session.commit()
        
        print("\n" + "="*50)
        print(f"İşlem Tamamlandı!")
        print(f"  Yeni eklenen: {count}")
        print(f"  Güncellenen: {updated}")
        print(f"  Atlanan: {skipped}")
        print(f"  Toplam işlenen: {count + updated}")
        print("="*50)

if __name__ == '__main__':
    import_veri_csv()
