import db from '../../config/database';
import { logger } from '../../utils/logger';

export enum CreativeTaskType {
  TTS = 'TTS',
  IMAGE_MAIN = 'IMAGE_MAIN',
  IMAGE_DETAIL = 'IMAGE_DETAIL',
  VIDEO_GEN = 'VIDEO_GEN',
  VIDEO_TRANSLATE = 'VIDEO_TRANSLATE'
}

export enum CreativeTaskStatus {
  PENDING = 'PENDING',
  PROCESSING = 'PROCESSING',
  COMPLETED = 'COMPLETED',
  FAILED = 'FAILED'
}

export interface CreativeTask {
  id?: string;
  tenant_id: string;
  type: CreativeTaskType;
  params: any; // JSON string in DB
  status: CreativeTaskStatus;
  result_url?: string;
  error_message?: string;
  created_at?: Date;
  updated_at?: Date;
}

/**
 * [BIZ_CRE_01] 多模态 AI 创作服务
 */
export class CreativeService {
  private static readonly TASK_TABLE = 'cf_creative_tasks';
  private static readonly ASSET_TABLE = 'cf_media_assets';

  static async initTable() {
    const hasTaskTable = await db.schema.hasTable(this.TASK_TABLE);
    if (!hasTaskTable) {
      logger.info(`📦 Creating ${this.TASK_TABLE} table...`);
      await db.schema.createTable(this.TASK_TABLE, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('type', 32).notNullable();
        table.json('params').notNullable();
        table.string('status', 32).defaultTo(CreativeTaskStatus.PENDING);
        table.string('result_url', 500);
        table.text('error_message');
        table.timestamps(true, true);
        table.index(['tenant_id', 'status']);
      });
    }

    const hasAssetTable = await db.schema.hasTable(this.ASSET_TABLE);
    if (!hasAssetTable) {
      logger.info(`📦 Creating ${this.ASSET_TABLE} table...`);
      await db.schema.createTable(this.ASSET_TABLE, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('type', 32).notNullable(); // IMAGE, VIDEO, AUDIO
        table.string('url', 500).notNullable();
        table.json('metadata');
        table.string('related_product_id', 64);
        table.timestamps(true, true);
        table.index(['tenant_id', 'related_product_id']);
      });
    }
  }

  /**
   * 创建创作任务
   */
  static async createTask(data: Partial<CreativeTask>): Promise<string> {
    const id = `CRE-${Date.now()}`;
    await db(this.TASK_TABLE).insert({
      ...data,
      id,
      params: JSON.stringify(data.params),
      status: CreativeTaskStatus.PENDING,
      created_at: db.fn.now(),
      updated_at: db.fn.now()
    });

    // 异步触发 AI 生成逻辑
    this.processTask(id).catch(err => {
      logger.error(`[Creative] Task ${id} trigger failed: ${err.message}`);
    });

    return id;
  }

  /**
   * 处理创作任务 (模拟 AI 调用)
   */
  private static async processTask(taskId: string) {
    const task = await db(this.TASK_TABLE).where({ id: taskId }).first();
    if (!task) return;

    await db(this.TASK_TABLE).where({ id: taskId }).update({ 
      status: CreativeTaskStatus.PROCESSING,
      updated_at: db.fn.now() 
    });

    try {
      logger.info(`[Creative] Processing ${task.type} task: ${taskId}`);
      
      // 模拟 AI 生成延迟
      await new Promise(resolve => setTimeout(resolve, 3000));

      let resultUrl = "";
      if (task.type === CreativeTaskType.TTS) {
        resultUrl = `https://assets.crawlful.com/audio/${taskId}.mp3`;
      } else if (task.type === CreativeTaskType.IMAGE_MAIN) {
        resultUrl = `https://assets.crawlful.com/images/${taskId}.jpg`;
      }

      await db(this.TASK_TABLE).where({ id: taskId }).update({
        status: CreativeTaskStatus.COMPLETED,
        result_url: resultUrl,
        updated_at: db.fn.now()
      });

      // 自动存入素材库
      await db(this.ASSET_TABLE).insert({
        id: `AST-${Date.now()}`,
        tenant_id: task.tenant_id,
        type: task.type.includes('IMAGE') ? 'IMAGE' : (task.type === 'TTS' ? 'AUDIO' : 'VIDEO'),
        url: resultUrl,
        metadata: task.params,
        created_at: db.fn.now(),
        updated_at: db.fn.now()
      });

      logger.info(`[Creative] Task ${taskId} COMPLETED.`);
    } catch (err: any) {
      await db(this.TASK_TABLE).where({ id: taskId }).update({
        status: CreativeTaskStatus.FAILED,
        error_message: err.message,
        updated_at: db.fn.now()
      });
    }
  }

  /**
   * 获取任务状态
   */
  static async getTask(taskId: string) {
    return db(this.TASK_TABLE).where({ id: taskId }).first();
  }

  /**
   * 获取素材库列表
   */
  static async getAssets(tenantId: string, type?: string) {
    let query = db(this.ASSET_TABLE).where({ tenant_id: tenantId });
    if (type) query = query.andWhere({ type });
    return query.orderBy('created_at', 'desc');
  }
}
