#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# ============================================================
# 🚀 Passenger WSGI - بازار آنلاین ۷۲۴
# ============================================================

# ===== IMPORTS =====
import json
import os
import sys
import locale
import re
from datetime import datetime, timedelta

# ===== تنظیم locale =====
try:
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
except:
    try:
        locale.setlocale(locale.LC_ALL, 'C.UTF-8')
    except:
        pass

# ===== تنظیم UTF-8 =====
if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')
else:
    import codecs
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)

# ===== مسیر پروژه =====
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, PROJECT_PATH)

# ===== ایمپورت اپلیکیشن =====
from app import app as application
from app import db, User, Setting, Category, Brand, Product, Coupon, generate_slug

# ===== تنظیمات محیط =====
os.environ['FLASK_ENV'] = 'production'
os.environ['FLASK_DEBUG'] = '0'


# ============================================================
# 🚀 تابع مقداردهی اولیه
# ============================================================
def init_database():
    with application.app_context():
        from app import (
            db, User, Setting, Category, Brand, Product, 
            ProductImage, ProductSpec, Keyword, SeoPage, 
            ShippingMethod, Reward
        )

        print("🌸 شروع مقداردهی اولیه دیتابیس...")

        # ===== ایجاد جداول =====
        db.create_all()
        print("✅ جداول ایجاد شدند")

        # ===== ایجاد ادمین =====
        if not User.query.filter_by(role='admin').first():
# جایی که ادمین ساخته میشه
            admin = User(
                username='admin',
                email='admin@onlinemarket724.ir',
                full_name='مدیر فروشگاه',
                phone='09123456789',  # ← یه شماره پیش‌فرض بذار
                role='admin',
                is_active=True
            )
            admin.set_password('admin123')
            db.session.add(admin)
            db.session.flush()

            try:
                reward = Reward(user_id=admin.id, points=1000, level='پلاتینیوم')
                db.session.add(reward)
            except:
                pass

            db.session.commit()
            print("✅ ادمین ایجاد شد: admin / admin123")

        # ===== تنظیمات سایت =====
        if not Setting.query.first():
            setting = Setting(
                site_name='بازار آنلاین ۷۲۴',
                site_logo='',
                site_favicon='',
                site_email='info@onlinemarket724.ir',
                site_phone='۰۲۱-۱۲۳۴۵۶۷۸',
                site_address='تهران، خیابان صنعت، پلاک ۱۲',
                footer_text='بازار آنلاین ۷۲۴ - مرجع تخصصی تجهیزات صنعتی و ابزارآلات',
                currency='تومان',
                tax_percent=0,
                meta_title='بازار آنلاین ۷۲۴ | مرجع تخصصی تجهیزات صنعتی و ابزارآلات',
                meta_description='خرید انواع تجهیزات صنعتی، قطعات الکترونیک، ابزارآلات و ماشین‌آلات با بهترین قیمت و کیفیت از بازار آنلاین ۷۲۴',
                seo_keywords='بازار آنلاین 724, onlinemarket724, تجهیزات صنعتی, قطعات صنعتی, ابزارآلات, ماشین‌آلات',
                social_media=json.dumps({
                    'instagram': 'https://instagram.com/onlinemarket724',
                    'telegram': 'https://t.me/onlinemarket724',
                    'whatsapp': 'https://wa.me/989123456789',
                    'linkedin': 'https://linkedin.com/company/onlinemarket724',
                    'aparat': 'https://aparat.com/onlinemarket724'
                }),
                maintenance_mode=False
            )
            db.session.add(setting)
            db.session.commit()
            print("✅ تنظیمات سایت ایجاد شد")

        # ===== دسته‌بندی‌ها =====
        categories_data = [
            {'name': 'قطعات یخچال', 'slug': 'refrigerator-parts'},
            {'name': 'قطعات لباسشویی', 'slug': 'washing-machine-parts'},
            {'name': 'پمپ آب', 'slug': 'water-pumps'},
            {'name': 'ابزار صنعتی', 'slug': 'industrial-tools'},
            {'name': 'کمپرسور', 'slug': 'compressors'},
            {'name': 'موتور الکتریکی', 'slug': 'electric-motors'},
            {'name': 'شیرآلات صنعتی', 'slug': 'industrial-valves'},
            {'name': 'بلبرینگ', 'slug': 'bearings'},
            {'name': 'ترموستات', 'slug': 'thermostats'},
            {'name': 'فیلتر', 'slug': 'filters'}
        ]

        categories = {}
        for cat_data in categories_data:
            category = Category.query.filter_by(slug=cat_data['slug']).first()
            if not category:
                category = Category(**cat_data)
                db.session.add(category)
                db.session.flush()
            categories[cat_data['slug']] = category

        # ===== برندها =====
        brands_data = [
            {'name': 'ال‌جی', 'slug': 'lg'},
            {'name': 'سامسونگ', 'slug': 'samsung'},
            {'name': 'اسنوا', 'slug': 'snowa'},
            {'name': 'بوش', 'slug': 'bosch'},
            {'name': 'پنتاکس', 'slug': 'pentax'},
            {'name': 'هیدرولیک', 'slug': 'hydraulic'},
            {'name': 'SKF', 'slug': 'skf'},
            {'name': 'پارس', 'slug': 'pars'},
            {'name': 'ایرج', 'slug': 'iraj'}
        ]

        brands = {}
        for brand_data in brands_data:
            brand = Brand.query.filter_by(slug=brand_data['slug']).first()
            if not brand:
                brand = Brand(**brand_data)
                db.session.add(brand)
                db.session.flush()
            brands[brand_data['slug']] = brand

        # ===== روش‌های ارسال =====
        shipping_methods = [
            {'name': 'پیک موتوری', 'base_cost': 80000, 'cost_per_kg': 5000, 'free_shipping_threshold': 5000000},
            {'name': 'پست پیشتاز', 'base_cost': 50000, 'cost_per_kg': 3000, 'free_shipping_threshold': 8000000},
            {'name': 'تیپاکس', 'base_cost': 70000, 'cost_per_kg': 4000, 'free_shipping_threshold': 6000000}
        ]

        for sm_data in shipping_methods:
            method = ShippingMethod.query.filter_by(name=sm_data['name']).first()
            if not method:
                method = ShippingMethod(**sm_data, is_active=True)
                db.session.add(method)

        db.session.commit()
        print("✅ دسته‌بندی‌ها، برندها و روش‌های ارسال ایجاد شدند")

        # ===== محصولات نمونه =====
        products_data = [
            {
                'title': 'کمپرسور یخچال ال‌جی ۱۲۰ وات',
                'category': categories.get('refrigerator-parts'),
                'brand': brands.get('lg'),
                'price': 2500000,
                'stock_quantity': 25,
                'weight': 5.5,
                'shipping_cost': 120000,
                'description': 'کمپرسور اصلی یخچال ال‌جی با توان ۱۲۰ وات - مناسب برای یخچال‌های ۱۲ تا ۱۶ فوت',
                'short_description': 'کمپرسور یخچال ال‌جی اصل، توان ۱۲۰ وات',
                'discount_percent': 20,
                'is_featured': True
            },
            {
                'title': 'ترموستات یخچال سامسونگ دیجیتال',
                'category': categories.get('refrigerator-parts'),
                'brand': brands.get('samsung'),
                'price': 850000,
                'stock_quantity': 40,
                'weight': 0.3,
                'shipping_cost': 50000,
                'description': 'ترموستات دیجیتال یخچال سامسونگ با نمایشگر ال‌سی‌دی',
                'short_description': 'ترموستات دیجیتال سامسونگ اصل',
                'discount_percent': 15,
                'is_new': True
            },
            {
                'title': 'موتور لباسشویی ال‌جی ۶ کیلوگرم',
                'category': categories.get('washing-machine-parts'),
                'brand': brands.get('lg'),
                'price': 3200000,
                'stock_quantity': 18,
                'weight': 8.0,
                'shipping_cost': 150000,
                'description': 'موتور اصلی لباسشویی ال‌جی با ظرفیت ۶ کیلوگرم - اینورتر دیجیتال',
                'short_description': 'موتور لباسشویی ال‌جی ۶ کیلوگرم اصل',
                'discount_percent': 20,
                'is_featured': True
            },
            {
                'title': 'پمپ آب خانگی پنتاکس ۰.۵ اسب',
                'category': categories.get('water-pumps'),
                'brand': brands.get('pentax'),
                'price': 5800000,
                'stock_quantity': 12,
                'weight': 15.0,
                'shipping_cost': 200000,
                'description': 'پمپ آب خانگی پنتاکس با قدرت ۰.۵ اسب بخار - مناسب برای منازل مسکونی',
                'short_description': 'پمپ آب پنتاکس ۰.۵ اسب اصل',
                'discount_percent': 12,
                'is_featured': True
            },
            {
                'title': 'دریل برقی ۱۵۰۰ وات - بوش',
                'category': categories.get('industrial-tools'),
                'brand': brands.get('bosch'),
                'price': 6500000,
                'stock_quantity': 20,
                'weight': 3.5,
                'shipping_cost': 120000,
                'description': 'دریل برقی بوش با قدرت ۱۵۰۰ وات - مجهز به سیستم ضربه‌ای',
                'short_description': 'دریل برقی بوش ۱۵۰۰ وات حرفه‌ای',
                'discount_percent': 10,
                'is_featured': True
            },
            {
                'title': 'بلبرینگ صنعتی SKF ۶۲۰۵',
                'category': categories.get('bearings'),
                'brand': brands.get('skf'),
                'price': 450000,
                'stock_quantity': 45,
                'weight': 0.3,
                'shipping_cost': 40000,
                'description': 'بلبرینگ صنعتی SKF مدل ۶۲۰۵ - اصل سوئدی',
                'short_description': 'بلبرینگ SKF ۶۲۰۵ اصل',
                'discount_percent': 5
            },
            {
                'title': 'شیر توپی برنجی ۱ اینچ - هیدرولیک',
                'category': categories.get('industrial-valves'),
                'brand': brands.get('hydraulic'),
                'price': 580000,
                'stock_quantity': 60,
                'weight': 1.2,
                'shipping_cost': 60000,
                'description': 'شیر توپی برنجی سایز ۱ اینچ - مناسب برای سیستم‌های آبرسانی',
                'short_description': 'شیر توپی برنجی ۱ اینچ هیدرولیک',
                'discount_percent': 10
            },
            {
                'title': 'فیلتر هوا صنعتی ۱۰ اینچ - پارس',
                'category': categories.get('filters'),
                'brand': brands.get('pars'),
                'price': 320000,
                'stock_quantity': 50,
                'weight': 0.5,
                'shipping_cost': 35000,
                'description': 'فیلتر هوا صنعتی سایز ۱۰ اینچ - مناسب برای کمپرسورها',
                'short_description': 'فیلتر هوا صنعتی ۱۰ اینچ پارس',
                'discount_percent': 8
            },
            {
                'title': 'پمپ تخلیه لباسشویی سامسونگ',
                'category': categories.get('washing-machine-parts'),
                'brand': brands.get('samsung'),
                'price': 680000,
                'stock_quantity': 30,
                'weight': 0.8,
                'shipping_cost': 45000,
                'description': 'پمپ تخلیه آب لباسشویی سامسونگ اصل - مناسب برای مدل‌های ۶ تا ۱۰ کیلوگرم',
                'short_description': 'پمپ تخلیه سامسونگ اصل',
                'discount_percent': 10
            },
            {
                'title': 'پمپ آب صنعتی ۲ اسب - هیدرولیک',
                'category': categories.get('water-pumps'),
                'brand': brands.get('hydraulic'),
                'price': 12500000,
                'stock_quantity': 8,
                'weight': 35.0,
                'shipping_cost': 350000,
                'description': 'پمپ آب صنعتی با قدرت ۲ اسب بخار - مناسب برای مصارف کشاورزی و صنعتی',
                'short_description': 'پمپ آب صنعتی ۲ اسب هیدرولیک',
                'discount_percent': 8,
                'is_featured': True
            }
        ]

        product_count = 0
        for p_data in products_data:
            if not p_data['category'] or not p_data['brand']:
                continue

            existing = Product.query.filter_by(title=p_data['title']).first()
            if existing:
                continue

            # ===== تولید اسلاگ با تابع generate_slug =====
            slug = generate_slug(p_data['title'])

            product = Product(
                title=p_data['title'],
                slug=slug,
                category_id=p_data['category'].id,
                brand_id=p_data['brand'].id,
                price=p_data['price'],
                compare_price=int(p_data['price'] * 1.2),
                stock_quantity=p_data['stock_quantity'],
                weight=p_data['weight'],
                shipping_cost=p_data['shipping_cost'],
                description=p_data['description'],
                short_description=p_data['short_description'],
                discount_percent=p_data.get('discount_percent', 0),
                is_featured=p_data.get('is_featured', False),
                is_new=p_data.get('is_new', False),
                is_active=True,
                seo_title=p_data['title']
            )

            if product.discount_percent > 0:
                product.discount_price = int(product.price * (1 - product.discount_percent / 100))

            db.session.add(product)
            db.session.flush()

            specs = {'ولتاژ': '۲۲۰ ولت', 'جنس': 'فلز', 'ساخت': 'اصل'}
            for key, value in specs.items():
                spec = ProductSpec(product_id=product.id, spec_key=key, spec_value=value)
                db.session.add(spec)

            product_count += 1

        db.session.commit()
        print(f"✅ {product_count} محصول جدید ایجاد شد")

        # ===== کلمات کلیدی و صفحات سئو =====
        keywords_data = [
            'خرید قطعات یخچال',
            'قیمت کمپرسور یخچال',
            'قطعات لباسشویی اصل',
            'پمپ آب خانگی',
            'خرید پمپ آب صنعتی',
            'ابزار صنعتی بوش',
            'بلبرینگ SKF',
            'خرید تجهیزات صنعتی',
            'ابزارآلات صنعتی'
        ]

        keyword_count = 0
        for kw_text in keywords_data:
            existing = Keyword.query.filter_by(keyword=kw_text).first()
            if existing:
                continue

            slug = generate_slug(kw_text)
            
            keyword = Keyword(
                keyword=kw_text,
                slug=slug,
                category_id=categories.get('refrigerator-parts', {}).id
            )
            db.session.add(keyword)
            db.session.flush()

            seo_page = SeoPage(
                keyword_id=keyword.id,
                title=f"خرید {kw_text} با بهترین قیمت در بازار آنلاین ۷۲۴",
                description=f"مشاهده و خرید انواع {kw_text} با قیمت مناسب و کیفیت عالی از بازار آنلاین ۷۲۴",
                content=f"<h1>خرید {kw_text}</h1><p>بهترین محصولات مربوط به {kw_text} را در این صفحه مشاهده کنید. بازار آنلاین ۷۲۴ مرجع تخصصی تجهیزات صنعتی و ابزارآلات.</p>",
                meta_title=f"خرید {kw_text} | قیمت و مشخصات | بازار آنلاین ۷۲۴",
                meta_description=f"خرید اینترنتی {kw_text} با بهترین قیمت از بازار آنلاین ۷۲۴",
                slug=slug
            )
            db.session.add(seo_page)
            keyword_count += 1

        db.session.commit()
        print(f"✅ {keyword_count} کلمه کلیدی و صفحه سئو ایجاد شد")

        print("🌸 مقداردهی اولیه با موفقیت کامل شد!")
        print(f"📊 آمار:")
        print(f"   - محصولات: {Product.query.count()}")
        print(f"   - دسته‌بندی‌ها: {Category.query.count()}")
        print(f"   - برندها: {Brand.query.count()}")
        print(f"   - کاربران: {User.query.count()}")


# ============================================================
# 🚀 اجرا
# ============================================================
init_database()

print("🌸 بازار آنلاین ۷۲۴ - راه‌اندازی شد!")
print("🔗 آدرس: http://localhost:5000")
print("👤 ادمین: admin / admin123")
print("📧 ایمیل: admin@onlinemarket724.ir")
print("🌐 دامنه: onlinemarket724.ir")