import sqlite3
from config import Config
import logging
import json

logger = logging.getLogger(__name__)

class Database:
    def __init__(self):
        self.db_path = 'bot.db'
        self.conn = None
        self.connect()
        self.create_tables()
    
    def connect(self):
        try:
            self.conn = sqlite3.connect(self.db_path)
            self.conn.row_factory = sqlite3.Row
            logger.info("✅ اتصال به دیتابیس SQLite برقرار شد")
        except Exception as e:
            logger.error(f"❌ خطا در اتصال به دیتابیس: {e}")
            raise
    
    def create_tables(self):
        cursor = self.conn.cursor()
        
        # جدول کاربران (بدون فیلد کد ملی)
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                telegram_id INTEGER UNIQUE NOT NULL,
                username TEXT,
                first_name TEXT,
                last_name TEXT,
                personal_code TEXT,
                phone_number TEXT,
                video_file_id TEXT,
                video_size INTEGER,
                status TEXT DEFAULT 'start',
                registered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)
        
        # جدول لاگ ادمین‌ها
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS admin_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                admin_id INTEGER,
                action TEXT,
                target_user_id INTEGER,
                details TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)
        
        self.conn.commit()
        cursor.close()
        logger.info("✅ جداول دیتابیس ایجاد شدند")
    
    # ==================== متدهای کاربر ====================
    
    def get_user(self, telegram_id):
        """دریافت اطلاعات یک کاربر"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT * FROM users WHERE telegram_id = ?", (telegram_id,))
        user = cursor.fetchone()
        cursor.close()
        return user
    
    def create_or_update_user(self, telegram_id, username=None, first_name=None, last_name=None):
        """ایجاد یا بروزرسانی کاربر"""
        cursor = self.conn.cursor()
        cursor.execute("""
            INSERT INTO users (telegram_id, username, first_name, last_name, status)
            VALUES (?, ?, ?, ?, 'start')
            ON CONFLICT (telegram_id) 
            DO UPDATE SET 
                username = excluded.username,
                first_name = excluded.first_name,
                last_name = excluded.last_name,
                updated_at = CURRENT_TIMESTAMP
        """, (telegram_id, username, first_name, last_name))
        self.conn.commit()
        cursor.close()
    
    def update_user_status(self, telegram_id, status):
        """بروزرسانی وضعیت کاربر"""
        cursor = self.conn.cursor()
        cursor.execute("""
            UPDATE users 
            SET status = ?, updated_at = CURRENT_TIMESTAMP
            WHERE telegram_id = ?
        """, (status, telegram_id))
        self.conn.commit()
        cursor.close()
    
    def update_user_info(self, telegram_id, field, value):
        """بروزرسانی یک فیلد از کاربر"""
        cursor = self.conn.cursor()
        query = f"UPDATE users SET {field} = ?, updated_at = CURRENT_TIMESTAMP WHERE telegram_id = ?"
        cursor.execute(query, (value, telegram_id))
        self.conn.commit()
        cursor.close()
    
    # ==================== متدهای ویدیو ====================
    
    def save_video_info(self, telegram_id, file_id, file_size):
        """ذخیره یک ویدیو (برای سازگاری با نسخه قبلی)"""
        cursor = self.conn.cursor()
        cursor.execute("""
            UPDATE users 
            SET video_file_id = ?, 
                video_size = ?,
                status = 'completed',
                updated_at = CURRENT_TIMESTAMP
            WHERE telegram_id = ?
        """, (file_id, file_size, telegram_id))
        self.conn.commit()
        cursor.close()
    
    def save_videos_info(self, telegram_id, video_ids):
        """ذخیره چند ویدیو برای یک کاربر (به صورت JSON)"""
        cursor = self.conn.cursor()
        
        # تبدیل لیست به JSON
        videos_json = json.dumps(video_ids)
        video_count = len(video_ids)
        
        cursor.execute("""
            UPDATE users 
            SET video_file_id = ?, 
                video_size = ?,
                status = 'completed',
                updated_at = CURRENT_TIMESTAMP
            WHERE telegram_id = ?
        """, (videos_json, video_count, telegram_id))
        
        self.conn.commit()
        cursor.close()
    
    def get_user_videos(self, telegram_id):
        """دریافت لیست ویدیوهای یک کاربر"""
        user = self.get_user(telegram_id)
        if not user or not user['video_file_id']:
            return []
        
        try:
            video_ids = json.loads(user['video_file_id'])
            if isinstance(video_ids, list):
                return video_ids
            else:
                return [video_ids]  # اگر یک ویدیو بود
        except:
            return [user['video_file_id']]  # اگر JSON نبود
    
    def get_video_count(self, telegram_id):
        """دریافت تعداد ویدیوهای یک کاربر"""
        videos = self.get_user_videos(telegram_id)
        return len(videos)
    
    # ==================== متدهای لیست و جستجو ====================
    
    def get_all_users(self, status=None):
        """دریافت لیست همه کاربران (با فیلتر وضعیت)"""
        cursor = self.conn.cursor()
        if status:
            cursor.execute("SELECT * FROM users WHERE status = ? ORDER BY registered_at DESC", (status,))
        else:
            cursor.execute("SELECT * FROM users ORDER BY registered_at DESC")
        users = cursor.fetchall()
        cursor.close()
        return users
    
    def get_completed_users(self):
        """دریافت کاربران تکمیل شده (ویدیو ارسال کرده‌اند)"""
        return self.get_all_users('completed')
    
    def get_pending_users(self):
        """دریافت کاربران در انتظار (هنوز ویدیو ارسال نکرده‌اند)"""
        return self.get_all_users('awaiting_video')
    
    def search_users(self, keyword):
        """جستجوی کاربران بر اساس نام یا کد پرسنلی"""
        cursor = self.conn.cursor()
        cursor.execute("""
            SELECT * FROM users 
            WHERE first_name LIKE ? 
            OR last_name LIKE ? 
            OR personal_code LIKE ?
            OR username LIKE ?
            ORDER BY registered_at DESC
        """, (f'%{keyword}%', f'%{keyword}%', f'%{keyword}%', f'%{keyword}%'))
        users = cursor.fetchall()
        cursor.close()
        return users
    
    def delete_user(self, telegram_id):
        """حذف یک کاربر"""
        cursor = self.conn.cursor()
        cursor.execute("DELETE FROM users WHERE telegram_id = ?", (telegram_id,))
        self.conn.commit()
        cursor.close()
    
    def delete_all_users(self):
        """حذف همه کاربران (هشدار!)"""
        cursor = self.conn.cursor()
        cursor.execute("DELETE FROM users")
        self.conn.commit()
        cursor.close()
    
    # ==================== متدهای آمار ====================
    
    def get_stats(self):
        """دریافت آمار کلی"""
        cursor = self.conn.cursor()
        
        cursor.execute("SELECT COUNT(*) FROM users")
        total = cursor.fetchone()[0]
        
        cursor.execute("SELECT COUNT(*) FROM users WHERE status = 'completed'")
        completed = cursor.fetchone()[0]
        
        cursor.execute("SELECT COUNT(*) FROM users WHERE status = 'awaiting_video'")
        pending = cursor.fetchone()[0]
        
        cursor.execute("SELECT COUNT(*) FROM users WHERE status = 'start'")
        not_started = cursor.fetchone()[0]
        
        cursor.close()
        
        return {
            'total': total,
            'completed': completed,
            'pending': pending,
            'not_started': not_started
        }
    
    # ==================== متدهای لاگ ====================
    
    def log_admin_action(self, admin_id, action, target_user_id=None, details=None):
        """ثبت لاگ فعالیت‌های ادمین"""
        cursor = self.conn.cursor()
        cursor.execute("""
            INSERT INTO admin_logs (admin_id, action, target_user_id, details)
            VALUES (?, ?, ?, ?)
        """, (admin_id, action, target_user_id, details))
        self.conn.commit()
        cursor.close()
    
    def get_admin_logs(self, limit=50):
        """دریافت لاگ‌های اخیر ادمین"""
        cursor = self.conn.cursor()
        cursor.execute("""
            SELECT * FROM admin_logs 
            ORDER BY created_at DESC 
            LIMIT ?
        """, (limit,))
        logs = cursor.fetchall()
        cursor.close()
        return logs
    
    # ==================== متدهای ابزاری ====================
    
    def backup_database(self, backup_path):
        """بکاپ‌گیری از دیتابیس"""
        import shutil
        shutil.copy2(self.db_path, backup_path)
        logger.info(f"✅ بکاپ از دیتابیس گرفته شد: {backup_path}")
    
    def clear_video_data(self, telegram_id):
        """پاک کردن ویدیوهای یک کاربر (بدون حذف کاربر)"""
        cursor = self.conn.cursor()
        cursor.execute("""
            UPDATE users 
            SET video_file_id = NULL, 
                video_size = NULL,
                status = 'awaiting_video',
                updated_at = CURRENT_TIMESTAMP
            WHERE telegram_id = ?
        """, (telegram_id,))
        self.conn.commit()
        cursor.close()
    
    def close(self):
        """بستن اتصال دیتابیس"""
        if self.conn:
            self.conn.close()
            logger.info("✅ اتصال دیتابیس بسته شد")