#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
直接創建資料表腳本
"""

import pymysql

def create_tables():
    """創建所有需要的資料表"""
    
    # 資料表 DDL
    tables = {
        'dt_users': '''
        CREATE TABLE IF NOT EXISTS dt_users (
            id INT PRIMARY KEY AUTO_INCREMENT,
            username VARCHAR(100) NOT NULL UNIQUE COMMENT 'AD帳號',
            display_name VARCHAR(200) NOT NULL COMMENT '顯示名稱',
            email VARCHAR(255) NOT NULL COMMENT '電子郵件',
            department VARCHAR(100) COMMENT '部門',
            is_admin BOOLEAN DEFAULT FALSE COMMENT '是否為管理員',
            last_login TIMESTAMP NULL COMMENT '最後登入時間',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_username (username),
            INDEX idx_email (email)
        ) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        ''',
        
        'dt_translation_jobs': '''
        CREATE TABLE IF NOT EXISTS dt_translation_jobs (
            id INT PRIMARY KEY AUTO_INCREMENT,
            job_uuid VARCHAR(36) NOT NULL UNIQUE COMMENT '任務唯一識別碼',
            user_id INT NOT NULL COMMENT '使用者ID',
            original_filename VARCHAR(500) NOT NULL COMMENT '原始檔名',
            file_extension VARCHAR(10) NOT NULL COMMENT '檔案副檔名',
            file_size BIGINT NOT NULL COMMENT '檔案大小(bytes)',
            file_path VARCHAR(1000) NOT NULL COMMENT '檔案路徑',
            source_language VARCHAR(50) DEFAULT NULL COMMENT '來源語言',
            target_languages JSON NOT NULL COMMENT '目標語言陣列',
            status ENUM('PENDING', 'PROCESSING', 'COMPLETED', 'FAILED', 'RETRY') DEFAULT 'PENDING',
            progress DECIMAL(5,2) DEFAULT 0.00 COMMENT '處理進度(%)',
            retry_count INT DEFAULT 0 COMMENT '重試次數',
            error_message TEXT NULL COMMENT '錯誤訊息',
            total_tokens INT DEFAULT 0 COMMENT '總token數',
            total_cost DECIMAL(10,4) DEFAULT 0.0000 COMMENT '總成本',
            processing_started_at TIMESTAMP NULL COMMENT '開始處理時間',
            completed_at TIMESTAMP NULL COMMENT '完成時間',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_user_id (user_id),
            INDEX idx_job_uuid (job_uuid),
            INDEX idx_status (status),
            INDEX idx_created_at (created_at),
            FOREIGN KEY (user_id) REFERENCES dt_users(id) ON DELETE CASCADE
        ) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        ''',
        
        'dt_job_files': '''
        CREATE TABLE IF NOT EXISTS dt_job_files (
            id INT PRIMARY KEY AUTO_INCREMENT,
            job_id INT NOT NULL COMMENT '任務ID',
            file_type ENUM('ORIGINAL', 'TRANSLATED') NOT NULL COMMENT '檔案類型',
            language_code VARCHAR(50) NULL COMMENT '語言代碼(翻譯檔案)',
            filename VARCHAR(500) NOT NULL COMMENT '檔案名稱',
            file_path VARCHAR(1000) NOT NULL COMMENT '檔案路徑',
            file_size BIGINT NOT NULL COMMENT '檔案大小',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_job_id (job_id),
            INDEX idx_file_type (file_type),
            FOREIGN KEY (job_id) REFERENCES dt_translation_jobs(id) ON DELETE CASCADE
        ) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        ''',
        
        'dt_translation_cache': '''
        CREATE TABLE IF NOT EXISTS dt_translation_cache (
            id INT PRIMARY KEY AUTO_INCREMENT,
            source_text_hash VARCHAR(64) NOT NULL COMMENT '來源文字hash',
            source_language VARCHAR(50) NOT NULL COMMENT '來源語言',
            target_language VARCHAR(50) NOT NULL COMMENT '目標語言',
            source_text TEXT NOT NULL COMMENT '來源文字',
            translated_text TEXT NOT NULL COMMENT '翻譯文字',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            UNIQUE KEY uk_cache (source_text_hash, source_language, target_language),
            INDEX idx_languages (source_language, target_language)
        ) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        ''',
        
        'dt_api_usage_stats': '''
        CREATE TABLE IF NOT EXISTS dt_api_usage_stats (
            id INT PRIMARY KEY AUTO_INCREMENT,
            user_id INT NOT NULL COMMENT '使用者ID',
            job_id INT NULL COMMENT '任務ID',
            api_endpoint VARCHAR(200) NOT NULL COMMENT 'API端點',
            prompt_tokens INT DEFAULT 0 COMMENT 'Prompt token數',
            completion_tokens INT DEFAULT 0 COMMENT 'Completion token數',
            total_tokens INT DEFAULT 0 COMMENT '總token數',
            prompt_unit_price DECIMAL(10,8) DEFAULT 0.00000000 COMMENT '單價',
            prompt_price_unit VARCHAR(20) DEFAULT 'USD' COMMENT '價格單位',
            cost DECIMAL(10,4) DEFAULT 0.0000 COMMENT '成本',
            response_time_ms INT DEFAULT 0 COMMENT '回應時間(毫秒)',
            success BOOLEAN DEFAULT TRUE COMMENT '是否成功',
            error_message TEXT NULL COMMENT '錯誤訊息',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_user_id (user_id),
            INDEX idx_job_id (job_id),
            INDEX idx_created_at (created_at),
            FOREIGN KEY (user_id) REFERENCES dt_users(id) ON DELETE CASCADE,
            FOREIGN KEY (job_id) REFERENCES dt_translation_jobs(id) ON DELETE SET NULL
        ) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        ''',
        
        'dt_system_logs': '''
        CREATE TABLE IF NOT EXISTS dt_system_logs (
            id INT PRIMARY KEY AUTO_INCREMENT,
            level ENUM('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL') NOT NULL,
            module VARCHAR(100) NOT NULL COMMENT '模組名稱',
            user_id INT NULL COMMENT '使用者ID',
            job_id INT NULL COMMENT '任務ID',
            message TEXT NOT NULL COMMENT '日誌訊息',
            extra_data JSON NULL COMMENT '額外資料',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_level (level),
            INDEX idx_module (module),
            INDEX idx_user_id (user_id),
            INDEX idx_created_at (created_at),
            FOREIGN KEY (user_id) REFERENCES dt_users(id) ON DELETE SET NULL,
            FOREIGN KEY (job_id) REFERENCES dt_translation_jobs(id) ON DELETE SET NULL
        ) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        '''
    }
    
    try:
        # 建立資料庫連線
        connection = pymysql.connect(
            host='mysql.theaken.com',
            port=33306,
            user='A060',
            password='WLeSCi0yhtc7',
            database='db_A060',
            charset='utf8mb4'
        )
        
        cursor = connection.cursor()
        
        print("Creating database tables...")
        
        # 依序創建表格
        for table_name, sql in tables.items():
            print(f"Creating table: {table_name}")
            cursor.execute(sql)
            print(f"  - {table_name} created successfully")
        
        # 創建預設管理員用戶
        print("\nCreating default admin user...")
        admin_sql = '''
        INSERT IGNORE INTO dt_users (username, display_name, email, department, is_admin) 
        VALUES ('ymirliu', 'ymirliu', 'ymirliu@panjit.com.tw', 'IT', TRUE)
        '''
        cursor.execute(admin_sql)
        
        if cursor.rowcount > 0:
            print("  - Default admin user created")
        else:
            print("  - Default admin user already exists")
        
        # 提交更改
        connection.commit()
        connection.close()
        
        print("\n=== Database initialization completed ===")
        return True
        
    except Exception as e:
        print(f"Database initialization failed: {e}")
        return False

if __name__ == '__main__':
    create_tables()