#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ساخت دیتابیس جدید برای یک کاربر خاص
این اسکریپت:
1. دیتابیس جدید می‌سازد
2. همه اطلاعات از دیتابیس اصلی را کپی می‌کند (به جز لیدها، معاملات، فعالیت‌ها)
3. فقط لیدها، معاملات و فعالیت‌های کاربر مشخص شده را از اکسل import می‌کند
"""

import pandas as pd
import sqlite3
import shutil
import json
from datetime import datetime
import os
import sys

# ============================================
# تنظیمات
# ============================================

OLD_DB_FILE = 'crm_database (4).db'
NEW_DB_FILE = 'crm_database_zahoori.db'
BACKUP_DB_FILE = f'crm_database_backup_{datetime.now().strftime("%Y-%m-%d_%H%M%S")}.db'

EXCEL_FILES = {
    'leads': 'all leads in didar.xlsx',
    'activities': 'activities from didar.xlsx',
    'deals': 'deals from didar.xlsx'
}

# کاربر هدف
TARGET_USER = {
    'name': 'جانان ظهوری',
    'owner_id': '55f5c374-4cf0-4e3e-8386-96ac21e7ac79',
    'user_id': '6d5350f0-5ee7-47d3-9eef-094698f6d070'
}

stats = {
    'leads': {'total': 0, 'filtered': 0, 'imported': 0, 'failed': 0},
    'activities': {'total': 0, 'imported': 0, 'skipped': 0},
    'deals': {'total': 0, 'imported': 0, 'skipped': 0},
    'virtual_stages': {'created': 0},
    'errors': []
}

# ============================================
# توابع کمکی
# ============================================

def log_message(message):
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f"[{timestamp}] {message}")

def normalize_phone(phone):
    if pd.isna(phone) or not phone:
        return ''
    return ''.join(filter(str.isdigit, str(phone)))

def convert_persian_date(persian_date):
    if pd.isna(persian_date) or not persian_date:
        return None
    
    try:
        parts = str(persian_date).strip().split('/')
        if len(parts) != 3:
            return None
        
        year = int(parts[0])
        month = int(parts[1])
        day = int(parts[2])
        
        gregorian_year = year + 621
        gregorian_month = month
        gregorian_day = day
        
        return f"{gregorian_year:04d}-{gregorian_month:02d}-{gregorian_day:02d}"
    except:
        return None

def parse_json_phones(json_string):
    if pd.isna(json_string) or not json_string:
        return ''
    
    try:
        data = json.loads(str(json_string))
        if isinstance(data, list) and len(data) > 0:
            first_phone = data[0].get('شماره') or data[0].get('number', '')
            return normalize_phone(first_phone)
    except:
        pass
    
    return ''

def map_deal_status(status):
    if pd.isna(status) or not status:
        return 'Pending'
    
    status_str = str(status).strip()
    if status_str == 'موفق':
        return 'Won'
    if status_str == 'ناموفق':
        return 'Lost'
    return 'Pending'

def determine_virtual_stage_from_excel(contact_id, activities, deals):
    """تعیین Virtual Stage بر اساس Activities و Deals"""
    # 1. بررسی آخرین فعالیت
    if activities and len(activities) > 0:
        last_activity = activities[0]
        activity_type = str(last_activity.get('نوع فعالیت', '')).strip()
        result_note = str(last_activity.get('نتیجه فعالیت', '')).strip()
        
        if 'عدم پاسخ' in activity_type:
            return 'contact_no_answer'
        if 'پیگیری' in activity_type:
            return 'contact_followup'
        if 'پشتیبانی' in activity_type:
            return 'support'
        
        if 'لید با خرید قبلی' in result_note:
            return 'with_purchase'
        if 'لید بدون خرید قبلی' in result_note:
            return 'without_purchase'
    
    # 2. بررسی Deals
    if deals and len(deals) > 0:
        deal = deals[0]
        status = str(deal.get('وضعیت معامله', '')).strip()
        pipeline_stage = str(deal.get('مرحله کاریز معامله', '')).strip()
        
        if status == 'موفق':
            has_course_delivery = False
            if activities:
                for act in activities:
                    act_type = str(act.get('نوع فعالیت', '')).strip()
                    if 'دوره' in act_type or 'برگزاری' in act_type:
                        has_course_delivery = True
                        break
            
            if has_course_delivery:
                return 'course_delivered'
            
            return 'payment'
        
        if 'لید ورودی' in pipeline_stage:
            return 'new'
        if 'پرزنت' in pipeline_stage or 'پیگیری' in pipeline_stage:
            return 'contact_followup'
        if 'دریافت وجه' in pipeline_stage:
            return 'payment'
        if 'پشتیبانی' in pipeline_stage:
            return 'support'
        
        return 'deal_registered'
    
    # 3. پیش‌فرض
    return 'new'

# ============================================
# بررسی فایل‌ها
# ============================================

log_message("بررسی فایل‌ها...")

if not os.path.exists(OLD_DB_FILE):
    print(f"❌ دیتابیس قدیم یافت نشد: {OLD_DB_FILE}")
    sys.exit(1)

for key, file in EXCEL_FILES.items():
    if not os.path.exists(file):
        print(f"❌ فایل اکسل یافت نشد: {file}")
        sys.exit(1)

log_message("✅ همه فایل‌ها موجود هستند")
log_message(f"🎯 کاربر هدف: {TARGET_USER['name']} (Owner ID: {TARGET_USER['owner_id']})")

# ============================================
# بکاپ از دیتابیس فعلی
# ============================================

log_message("📦 ایجاد بکاپ از دیتابیس فعلی...")

try:
    if os.path.exists(OLD_DB_FILE):
        shutil.copy2(OLD_DB_FILE, BACKUP_DB_FILE)
        log_message(f"✅ بکاپ ایجاد شد: {BACKUP_DB_FILE}")
except Exception as e:
    log_message(f"⚠️ خطا در ایجاد بکاپ: {e}")

# ============================================
# ایجاد دیتابیس جدید
# ============================================

log_message("🗄️ ایجاد دیتابیس جدید...")

if os.path.exists(NEW_DB_FILE):
    os.remove(NEW_DB_FILE)

new_conn = sqlite3.connect(NEW_DB_FILE)
new_conn.execute('PRAGMA journal_mode=WAL;')
new_conn.execute('PRAGMA busy_timeout=30000;')
new_cursor = new_conn.cursor()

# ============================================
# ایجاد جداول
# ============================================

log_message("📋 ایجاد جداول...")

table_commands = [
    """CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        didar_user_id TEXT UNIQUE NOT NULL,
        email TEXT UNIQUE NOT NULL,
        first_name TEXT,
        last_name TEXT,
        display_name TEXT,
        username TEXT UNIQUE,
        password TEXT,
        role TEXT CHECK(role IN ('admin', 'agent')) DEFAULT 'agent',
        is_active INTEGER DEFAULT 1,
        api_key TEXT,
        last_sync DATETIME,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )""",
    """CREATE TABLE IF NOT EXISTS persons (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        didar_contact_id TEXT UNIQUE NOT NULL,
        owner_didar_id TEXT,
        code TEXT,
        first_name TEXT,
        last_name TEXT,
        mobile_phone TEXT,
        secondary_mobile_phone TEXT,
        work_phone TEXT,
        email TEXT,
        contact_type TEXT,
        city TEXT,
        job_title TEXT,
        acquaintance_source TEXT,
        acquaintance_detail TEXT,
        content_topic TEXT,
        national_id TEXT,
        has_previous_purchase INTEGER DEFAULT 0,
        birth_date DATE,
        register_time DATETIME,
        visibility_type TEXT,
        background_info TEXT,
        last_sync DATETIME,
        raw_json TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )""",
    """CREATE TABLE IF NOT EXISTS deals (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        didar_deal_id TEXT UNIQUE NOT NULL,
        owner_didar_id TEXT,
        contact_didar_id TEXT,
        title TEXT,
        code TEXT,
        status TEXT CHECK(status IN ('Pending', 'Won', 'Lost')),
        pipeline_stage_id TEXT,
        pipeline_stage_title TEXT,
        estimated_price REAL,
        final_price REAL,
        probability INTEGER,
        is_paid INTEGER DEFAULT 0,
        payment_short_link TEXT,
        register_time DATETIME,
        last_update_time DATETIME,
        won_time DATETIME,
        lost_time DATETIME,
        visibility_type TEXT,
        last_sync DATETIME,
        raw_json TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )""",
    """CREATE TABLE IF NOT EXISTS activities (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        didar_activity_id TEXT UNIQUE NOT NULL,
        activity_type_id TEXT NOT NULL,
        activity_type_title TEXT,
        owner_didar_id TEXT,
        deal_didar_id TEXT,
        contact_didar_id TEXT,
        title TEXT,
        note TEXT,
        result_note TEXT,
        is_done INTEGER DEFAULT 0,
        due_date DATETIME,
        done_date DATETIME,
        duration INTEGER,
        activity_category TEXT,
        direction TEXT CHECK(direction IN ('incoming', 'outgoing')),
        stage TEXT,
        register_date DATETIME,
        last_update_time DATETIME,
        last_sync DATETIME,
        raw_json TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )""",
    """CREATE TABLE IF NOT EXISTS virtual_stages (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        contact_didar_id TEXT NOT NULL,
        stage_name TEXT CHECK(stage_name IN (
            'inactive_failed', 'inactive_success', 'with_purchase', 'without_purchase',
            'new', 'contact_no_answer', 'contact_followup', 'deal_registered', 'payment', 
            'payment_followup', 'course_delivered', 'support', 'refer_crm'
        )),
        entered_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        last_activity_id TEXT,
        notes TEXT,
        UNIQUE(contact_didar_id, stage_name)
    )""",
    """CREATE TABLE IF NOT EXISTS config (
        key TEXT PRIMARY KEY,
        value TEXT,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )""",
    """CREATE TABLE IF NOT EXISTS sync_log (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        entity_type TEXT CHECK(entity_type IN ('user', 'person', 'deal', 'activity')),
        entity_id TEXT,
        action TEXT CHECK(action IN ('fetch', 'create', 'update')),
        status TEXT CHECK(status IN ('success', 'failed')),
        error_message TEXT,
        http_code INTEGER,
        response_data TEXT,
        synced_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )""",
    """CREATE TABLE IF NOT EXISTS pipeline_cache (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        pipeline_id TEXT UNIQUE NOT NULL,
        pipeline_title TEXT,
        stages_json TEXT,
        cached_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )""",
    """CREATE TABLE IF NOT EXISTS referrals (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        contact_didar_id TEXT NOT NULL,
        referrer_didar_id TEXT,
        note TEXT,
        phones TEXT,
        status TEXT DEFAULT 'pending',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )"""
]

for cmd in table_commands:
    try:
        new_cursor.execute(cmd)
    except Exception as e:
        log_message(f"⚠️ خطا در ایجاد جدول: {e}")

new_conn.commit()
log_message("✅ جداول ایجاد شدند")

# ============================================
# کپی جداول از دیتابیس قدیم (به جز لیدها، معاملات، فعالیت‌ها)
# ============================================

log_message("📥 کپی جداول از دیتابیس قدیم...")

try:
    old_conn = sqlite3.connect(OLD_DB_FILE)
    old_cursor = old_conn.cursor()
    
    # کپی users
    log_message("  - کپی users...")
    old_cursor.execute("SELECT * FROM users")
    users = old_cursor.fetchall()
    if users:
        user_columns = [description[0] for description in old_cursor.description]
        placeholders = ','.join(['?' for _ in user_columns])
        columns = ','.join(user_columns)
        insert_sql = f"INSERT OR REPLACE INTO users ({columns}) VALUES ({placeholders})"
        
        for user in users:
            new_cursor.execute(insert_sql, user)
        
        new_conn.commit()
        log_message(f"    ✅ {len(users)} کاربر کپی شد")
        
        # اصلاح didar_user_id کاربر هدف
        log_message(f"  - اصلاح didar_user_id برای {TARGET_USER['name']}...")
        target_user_row = new_cursor.execute(
            "SELECT id FROM users WHERE display_name LIKE ?",
            (f"%{TARGET_USER['name']}%",)
        ).fetchone()
        
        if target_user_row:
            new_cursor.execute(
                "UPDATE users SET didar_user_id = ? WHERE id = ?",
                (TARGET_USER['owner_id'], target_user_row[0])
            )
            new_conn.commit()
            log_message(f"    ✅ didar_user_id به {TARGET_USER['owner_id']} تغییر یافت")
        else:
            log_message(f"    ⚠️ کاربر {TARGET_USER['name']} پیدا نشد!")
    
    # کپی config
    log_message("  - کپی config...")
    old_cursor.execute("SELECT * FROM config")
    configs = old_cursor.fetchall()
    if configs:
        config_columns = [description[0] for description in old_cursor.description]
        placeholders = ','.join(['?' for _ in config_columns])
        columns = ','.join(config_columns)
        insert_sql = f"INSERT OR REPLACE INTO config ({columns}) VALUES ({placeholders})"
        
        for config in configs:
            new_cursor.execute(insert_sql, config)
        
        new_conn.commit()
        log_message(f"    ✅ {len(configs)} تنظیمات کپی شد")
    
    # کپی pipeline_cache
    log_message("  - کپی pipeline_cache...")
    old_cursor.execute("SELECT * FROM pipeline_cache")
    pipelines = old_cursor.fetchall()
    if pipelines:
        pipeline_columns = [description[0] for description in old_cursor.description]
        placeholders = ','.join(['?' for _ in pipeline_columns])
        columns = ','.join(pipeline_columns)
        insert_sql = f"INSERT OR REPLACE INTO pipeline_cache ({columns}) VALUES ({placeholders})"
        
        for pipeline in pipelines:
            new_cursor.execute(insert_sql, pipeline)
        
        new_conn.commit()
        log_message(f"    ✅ {len(pipelines)} pipeline کپی شد")
    
    old_conn.close()
    
except Exception as e:
    log_message(f"⚠️ خطا در کپی جداول: {e}")

# ============================================
# خواندن و Import لیدهای کاربر ظهوری
# ============================================

log_message("\n📖 شروع خواندن فایل‌های اکسل...")
log_message(f"🎯 فیلتر: فقط لیدهای {TARGET_USER['name']}")

# خواندن Leads
log_message("  - خواندن Leads...")
try:
    df_leads = pd.read_excel(EXCEL_FILES['leads'])
    stats['leads']['total'] = len(df_leads)
    log_message(f"    ✅ {len(df_leads)} لید خوانده شد")
    
    # فیلتر کردن بر اساس owner
    log_message(f"  - فیلتر کردن لیدهای {TARGET_USER['name']}...")
    filtered_leads = []
    for idx, row in df_leads.iterrows():
        owner_name = str(row.get('مسئول مشتری', '')).strip()
        # بررسی دقیق و جزئی
        if TARGET_USER['name'] in owner_name or owner_name in TARGET_USER['name']:
            filtered_leads.append(row)
    
    stats['leads']['filtered'] = len(filtered_leads)
    log_message(f"    ✅ {len(filtered_leads)} لید فیلتر شد")
    
    # Import Leads
    log_message("💾 Import لیدها...")
    imported_contact_ids = []
    
    insert_person_sql = """INSERT OR REPLACE INTO persons 
        (didar_contact_id, owner_didar_id, code, first_name, last_name, 
         mobile_phone, secondary_mobile_phone, work_phone, email, 
         contact_type, city, job_title, acquaintance_source, acquaintance_detail, 
         content_topic, register_time, visibility_type, has_previous_purchase, 
         last_sync, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"""
    
    batch_count = 0
    for row in filtered_leads:
        try:
            contact_id = str(row.get('کد دیدار مشتری', '')).strip()
            if not contact_id:
                continue
            
            first_name = str(row.get('نام مشتری', '')).strip() if pd.notna(row.get('نام مشتری')) else ''
            last_name = str(row.get('نام خانوادگی مشتری', '')).strip() if pd.notna(row.get('نام خانوادگی مشتری')) else ''
            mobile_phone = normalize_phone(row.get('تلفن همراه مشتری', ''))
            secondary_mobile = parse_json_phones(row.get('تلفن های دیگر مشتری', ''))
            work_phone = normalize_phone(row.get('تلفن ثابت مشتری', ''))
            email = str(row.get('ایمیل مشتری', '')).strip() if pd.notna(row.get('ایمیل مشتری')) else ''
            city = str(row.get('شهر_1', '')).strip() if pd.notna(row.get('شهر_1')) else ''
            job_title = str(row.get('شغل', '')).strip() if pd.notna(row.get('شغل')) else ''
            acquaintance_source = str(row.get('شیوه آشنایی', '')).strip() if pd.notna(row.get('شیوه آشنایی')) else ''
            acquaintance_detail = str(row.get('جزئیات شیوه آشنایی', '')).strip() if pd.notna(row.get('جزئیات شیوه آشنایی')) else ''
            content_topic = str(row.get('موضوع محتوا', '')).strip() if pd.notna(row.get('موضوع محتوا')) else ''
            register_time = convert_persian_date(row.get('تاریخ ثبت مشتری', ''))
            visibility_type = str(row.get('مجوز مشاهده مشتری', '')).strip() if pd.notna(row.get('مجوز مشاهده مشتری')) else ''
            code = contact_id
            
            new_cursor.execute(insert_person_sql, (
                contact_id, TARGET_USER['owner_id'], code, first_name, last_name,
                mobile_phone, secondary_mobile, work_phone, email,
                'Lead', city, job_title, acquaintance_source, acquaintance_detail,
                content_topic, register_time, visibility_type, 0
            ))
            
            imported_contact_ids.append(contact_id)
            stats['leads']['imported'] += 1
            batch_count += 1
            
            if batch_count % 100 == 0:
                new_conn.commit()
                log_message(f"    Import شده: {batch_count} لید...")
        
        except Exception as e:
            stats['leads']['failed'] += 1
            stats['errors'].append(f"Lead import error: {e}")
    
    new_conn.commit()
    log_message(f"    ✅ {stats['leads']['imported']} لید import شد")
    
except Exception as e:
    log_message(f"❌ خطا در خواندن Leads: {e}")
    stats['errors'].append(f"Leads read error: {e}")

# ============================================
# خواندن و Import Activities
# ============================================

log_message("\n📖 خواندن Activities...")

try:
    df_activities = pd.read_excel(EXCEL_FILES['activities'])
    stats['activities']['total'] = len(df_activities)
    log_message(f"    ✅ {len(df_activities)} فعالیت خوانده شد")
    
    # گروه‌بندی بر اساس contact_id (فقط برای لیدهای import شده)
    activities_by_contact = {}
    for idx, row in df_activities.iterrows():
        contact_id = str(row.get('کد اشخاص فعالیت', '')).strip()
        if contact_id and contact_id in imported_contact_ids:
            if contact_id not in activities_by_contact:
                activities_by_contact[contact_id] = []
            activities_by_contact[contact_id].append(row.to_dict())
    
    log_message(f"  - {len(activities_by_contact)} contact با فعالیت پیدا شد")
    
    # Import Activities
    log_message("💾 Import Activities...")
    
    insert_activity_sql = """INSERT OR REPLACE INTO activities 
        (didar_activity_id, activity_type_id, activity_type_title, owner_didar_id,
         contact_didar_id, title, note, result_note, is_done,
         due_date, done_date, register_date, last_sync, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"""
    
    activity_counter = 0
    for contact_id, activities in activities_by_contact.items():
        for activity in activities:
            try:
                activity_id = f'excel_{contact_id}_{activity_counter}'
                activity_type = str(activity.get('نوع فعالیت', '')).strip() if activity.get('نوع فعالیت') else ''
                title = str(activity.get('عنوان فعالیت', activity_type)).strip() if activity.get('عنوان فعالیت') else activity_type
                note = str(activity.get('متن فعالیت', '')).strip() if activity.get('متن فعالیت') else ''
                result_note = str(activity.get('نتیجه فعالیت', '')).strip() if activity.get('نتیجه فعالیت') else ''
                status = str(activity.get('وضعیت اجرای فعالیت', '')).strip() if activity.get('وضعیت اجرای فعالیت') else ''
                is_done = 1 if 'انجام شده' in status else 0
                due_date = convert_persian_date(activity.get('تاریخ برنامه ریزی شده اجرا فعالیت', ''))
                done_date = convert_persian_date(activity.get('تاریخ انجام شدن فعالیت', ''))
                register_date = due_date if due_date else datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                
                new_cursor.execute(insert_activity_sql, (
                    activity_id, 'excel_type', activity_type, TARGET_USER['owner_id'],
                    contact_id, title, note, result_note, is_done,
                    due_date, done_date, register_date
                ))
                
                activity_counter += 1
                stats['activities']['imported'] += 1
                
                if activity_counter % 100 == 0:
                    new_conn.commit()
                    log_message(f"    Import شده: {activity_counter} فعالیت...")
            
            except Exception as e:
                stats['activities']['skipped'] += 1
                stats['errors'].append(f"Activity import error: {e}")
    
    new_conn.commit()
    log_message(f"    ✅ {stats['activities']['imported']} فعالیت import شد")
    
except Exception as e:
    log_message(f"❌ خطا در خواندن Activities: {e}")
    stats['errors'].append(f"Activities read error: {e}")

# ============================================
# خواندن و Import Deals
# ============================================

log_message("\n📖 خواندن Deals...")

try:
    df_deals = pd.read_excel(EXCEL_FILES['deals'])
    stats['deals']['total'] = len(df_deals)
    log_message(f"    ✅ {len(df_deals)} معامله خوانده شد")
    
    # فیلتر Deals بر اساس imported contact ids
    deals_by_contact = {}
    for idx, row in df_deals.iterrows():
        contact_id = str(row.get('کد دیدار شخص معامله', '')).strip()
        if contact_id and contact_id in imported_contact_ids:
            if contact_id not in deals_by_contact:
                deals_by_contact[contact_id] = []
            deals_by_contact[contact_id].append(row.to_dict())
    
    log_message(f"  - {len(deals_by_contact)} contact با معامله پیدا شد")
    
    # Import Deals
    log_message("💾 Import Deals...")
    
    insert_deal_sql = """INSERT OR REPLACE INTO deals 
        (didar_deal_id, owner_didar_id, contact_didar_id, title, code, status,
         pipeline_stage_title, estimated_price, final_price, probability,
         register_time, won_time, visibility_type, last_sync, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"""
    
    deal_counter = 0
    for contact_id, deals in deals_by_contact.items():
        for deal in deals:
            try:
                deal_id = str(deal.get('کد دیدار معامله', '')).strip()
                if not deal_id:
                    deal_id = f'excel_{contact_id}_{deal_counter}'
                
                title = str(deal.get('عنوان معامله', '')).strip() if deal.get('عنوان معامله') else ''
                price = float(deal.get('ارزش معامله', 0)) if deal.get('ارزش معامله') else 0
                final_price = float(deal.get('مبلغ نهایی', price)) if deal.get('مبلغ نهایی') else price
                status = map_deal_status(deal.get('وضعیت معامله', ''))
                register_time = convert_persian_date(deal.get('تاریخ ایجاد معامله', ''))
                won_time = convert_persian_date(deal.get('تاریخ انجام معامله', '')) if status == 'Won' else None
                pipeline_stage_title = str(deal.get('مرحله کاریز معامله', '')).strip() if deal.get('مرحله کاریز معامله') else ''
                probability = int(deal.get('احتمال موفقیت معامله', 0)) if deal.get('احتمال موفقیت معامله') else 0
                visibility_type = str(deal.get('مجوز مشاهده معامله', '')).strip() if deal.get('مجوز مشاهده معامله') else ''
                
                new_cursor.execute(insert_deal_sql, (
                    deal_id, TARGET_USER['owner_id'], contact_id, title, deal_id, status,
                    pipeline_stage_title, price, final_price, probability,
                    register_time, won_time, visibility_type
                ))
                
                deal_counter += 1
                stats['deals']['imported'] += 1
                
                if deal_counter % 100 == 0:
                    new_conn.commit()
                    log_message(f"    Import شده: {deal_counter} معامله...")
            
            except Exception as e:
                stats['deals']['skipped'] += 1
                stats['errors'].append(f"Deal import error: {e}")
    
    new_conn.commit()
    log_message(f"    ✅ {stats['deals']['imported']} معامله import شد")
    
except Exception as e:
    log_message(f"❌ خطا در خواندن Deals: {e}")
    stats['errors'].append(f"Deals read error: {e}")

# ============================================
# ایجاد Virtual Stages
# ============================================

log_message("\n🎯 ایجاد Virtual Stages...")

try:
    insert_stage_sql = """INSERT OR REPLACE INTO virtual_stages (contact_didar_id, stage_name, entered_at)
        VALUES (?, ?, CURRENT_TIMESTAMP)"""
    
    stage_counter = 0
    for contact_id in imported_contact_ids:
        try:
            # دریافت Activities مرتبط
            new_cursor.execute("""
                SELECT activity_type_title, result_note 
                FROM activities 
                WHERE contact_didar_id = ? 
                ORDER BY register_date DESC, created_at DESC
            """, (contact_id,))
            activities_rows = new_cursor.fetchall()
            activities = [{'نوع فعالیت': row[0] or '', 'نتیجه فعالیت': row[1] or ''} for row in activities_rows]
            
            # دریافت Deals مرتبط
            new_cursor.execute("""
                SELECT status, pipeline_stage_title 
                FROM deals 
                WHERE contact_didar_id = ? 
                ORDER BY register_time DESC
            """, (contact_id,))
            deals_rows = new_cursor.fetchall()
            deals = []
            for row in deals_rows:
                status = 'موفق' if row[0] == 'Won' else ('ناموفق' if row[0] == 'Lost' else 'جاری')
                deals.append({'وضعیت معامله': status, 'مرحله کاریز معامله': row[1] or ''})
            
            # تعیین Virtual Stage
            virtual_stage = determine_virtual_stage_from_excel(contact_id, activities, deals)
            
            # ذخیره
            new_cursor.execute(insert_stage_sql, (contact_id, virtual_stage))
            
            stage_counter += 1
            stats['virtual_stages']['created'] += 1
            
            if stage_counter % 100 == 0:
                new_conn.commit()
                log_message(f"    ایجاد شده: {stage_counter} virtual stage...")
        
        except Exception as e:
            stats['errors'].append(f"Virtual stage error for {contact_id}: {e}")
    
    new_conn.commit()
    log_message(f"    ✅ {stats['virtual_stages']['created']} virtual stage ایجاد شد")
    
except Exception as e:
    log_message(f"❌ خطا در ایجاد Virtual Stages: {e}")
    stats['errors'].append(f"Virtual stages error: {e}")

# ============================================
# گزارش نهایی
# ============================================

log_message("\n" + "="*60)
log_message("✅ Import کامل انجام شد!")
log_message("="*60)
log_message(f"\n📊 آمار نهایی برای {TARGET_USER['name']}:")
log_message("  📋 لیدها:")
log_message(f"     - کل در اکسل: {stats['leads']['total']}")
log_message(f"     - فیلتر شده: {stats['leads']['filtered']}")
log_message(f"     - Import شده: {stats['leads']['imported']}")
log_message(f"     - خطا: {stats['leads']['failed']}")
log_message("  📞 فعالیت‌ها:")
log_message(f"     - کل در اکسل: {stats['activities']['total']}")
log_message(f"     - Import شده: {stats['activities']['imported']}")
log_message(f"     - Skip شده: {stats['activities']['skipped']}")
log_message("  💼 معاملات:")
log_message(f"     - کل در اکسل: {stats['deals']['total']}")
log_message(f"     - Import شده: {stats['deals']['imported']}")
log_message(f"     - Skip شده: {stats['deals']['skipped']}")
log_message("  🎯 Virtual Stages:")
log_message(f"     - ایجاد شده: {stats['virtual_stages']['created']}")

if stats['errors']:
    log_message(f"\n⚠️ خطاها ({len(stats['errors'])} مورد):")
    for error in stats['errors'][:10]:
        log_message(f"     - {error}")
    if len(stats['errors']) > 10:
        log_message(f"     ... و {len(stats['errors']) - 10} خطای دیگر")

log_message(f"\n📁 فایل‌ها:")
log_message(f"  - دیتابیس جدید: {NEW_DB_FILE}")
log_message(f"  - بکاپ دیتابیس: {BACKUP_DB_FILE}")
log_message("\n✅ آماده برای استفاده!")

new_conn.close()
print(f"\n✅ دیتابیس جدید ایجاد شد: {NEW_DB_FILE}")

