// 主动服务系统
import { generateId } from '../../utils/id';
import { createLogger } from '../../utils/logger';

const log = createLogger('Proactive');

export interface ScheduledTask {
  id: string;
  userId: string;
  channel: string;
  schedule: {
    type: 'once' | 'daily' | 'weekly' | 'cron';
    time: string;
    timezone: string;
  };
  task: {
    type: string;
    prompt: string;
  };
  status: 'active' | 'paused' | 'completed';
  lastRun?: Date;
  nextRun?: Date;
}

export class ProactiveServiceSystem {
  private tasks: Map<string, ScheduledTask> = new Map();
  private cronJobs: Map<string, any> = new Map();

  async scheduleTask(task: ScheduledTask): Promise<void> {
    task.id = task.id || this.generateId();
    task.status = 'active';
    
    this.tasks.set(task.id, task);

    // node-cron 集成（可选依赖）
    try {
      const cron = require('node-cron');
      const cronExpr = this.toCronExpression(task);
      if (cronExpr) {
        const job = cron.schedule(cronExpr, () => {
          log.info(`Cron triggered: ${task.id}`);
          // TODO: 执行实际任务逻辑
          task.lastRun = new Date();
        }, { timezone: task.schedule.timezone });
        this.cronJobs.set(task.id, job);
      }
    } catch {
      log.debug('node-cron not available, scheduling in-memory only');
    }

    log.info(`Task scheduled: ${task.id} (${task.schedule.type} at ${task.schedule.time})`);
  }

  async cancelTask(taskId: string): Promise<void> {
    const task = this.tasks.get(taskId);
    if (task) {
      task.status = 'paused';
      // TODO: 取消 cron job
    }
  }

  async listTasks(userId: string): Promise<ScheduledTask[]> {
    return Array.from(this.tasks.values()).filter(t => t.userId === userId);
  }

  private toCronExpression(task: ScheduledTask): string | null {
    const { type, time } = task.schedule;
    if (type === 'cron') return time; // already a cron expression

    // Parse HH:MM format
    const parts = time.split(':');
    if (parts.length !== 2) return null;
    const [hour, minute] = parts;

    switch (type) {
      case 'daily':
        return `${minute} ${hour} * * *`;
      case 'weekly':
        return `${minute} ${hour} * * 1`; // Monday
      case 'once':
        return null; // handled separately via setTimeout
      default:
        return null;
    }
  }

  private generateId(): string {
    return generateId('cron');
  }
}
