export interface StandingOrderDraft {
  name: string;
  description: string;
  trigger: {
    type: 'cron' | 'event' | 'threshold' | 'manual';
    cronExpression?: string;
    eventType?: string;
    thresholdCondition?: {
      metricType: string;
      operator: string;
      value: number;
      durationSeconds: number;
    };
  };
  targets: {
    serverIds?: string[];
    clusterIds?: string[];
    allServers?: boolean;
    environmentFilter?: string[];
    tagFilter?: Record<string, string>;
  };
  agentInstructions: {
    prompt: string;
    skills?: string[];
    maxRiskLevel: 0 | 1;
    maxTurns: number;
  };
  decisionBoundary: {
    allowedActions: string[];
    escalateConditions: string[];
    escalationRules: Array<{
      condition: string;
      channel: string;
      priority: string;
    }>;
  };
}

export class StandingOrderExtractorService {
  private readonly TASK_KEYWORDS = ['以后', '每天', '定时', '自动', '巡检', '清理', '检查', '定期'];

  detectTaskDefinitionIntent(message: string): boolean {
    return this.TASK_KEYWORDS.some(kw => message.includes(kw));
  }

  parseOrderDraft(agentOutput: string): StandingOrderDraft | null {
    try {
      const jsonMatch = agentOutput.match(/```json\n([\s\S]*?)\n```/);
      if (jsonMatch) {
        return JSON.parse(jsonMatch[1]) as StandingOrderDraft;
      }
      return null;
    } catch {
      return null;
    }
  }

  /**
   * Extracts standing order parameters from a conversation history.
   * Builds a structured prompt to identify trigger conditions, target servers,
   * commands to run, and schedule from the messages.
   * Returns a StandingOrderDraft if a standing order definition is detected, or null otherwise.
   */
  async extractFromConversation(
    messages: Array<{ role: string; content: string }>,
  ): Promise<StandingOrderDraft | null> {
    // Build the combined conversation text for analysis
    const conversationText = messages
      .map((m) => `[${m.role}]: ${m.content}`)
      .join('\n');

    // Check if the conversation contains any standing order intent
    const hasIntent = messages.some((m) => this.detectTaskDefinitionIntent(m.content));
    if (!hasIntent) return null;

    // Extract structured parameters from the conversation
    const draft = this.buildDraftFromConversation(conversationText);
    return draft;
  }

  private buildDraftFromConversation(text: string): StandingOrderDraft | null {
    // Attempt to extract a cron-like schedule
    const cronMatch = text.match(/(?:每天|daily)\s*(\d{1,2})[:\s时](\d{0,2})/);
    const triggerType = this.detectTriggerType(text);

    // Extract name/description from the conversation
    const nameMatch = text.match(/(?:任务|task|名称|name)[：:]\s*(.+)/i);
    const name = nameMatch ? nameMatch[1].trim() : '';
    const description = name || 'Auto-extracted standing order';

    if (!triggerType) return null;

    const draft: StandingOrderDraft = {
      name,
      description,
      trigger: {
        type: triggerType,
        ...(triggerType === 'cron' && cronMatch
          ? { cronExpression: `${cronMatch[2] || '0'} ${cronMatch[1]} * * *` }
          : {}),
      },
      targets: {
        allServers: text.includes('所有') || text.includes('all'),
      },
      agentInstructions: {
        prompt: text,
        maxRiskLevel: 0,
        maxTurns: 5,
      },
      decisionBoundary: {
        allowedActions: [],
        escalateConditions: [],
        escalationRules: [],
      },
    };

    return draft;
  }

  private detectTriggerType(text: string): StandingOrderDraft['trigger']['type'] | null {
    if (/每天|每周|每月|每小时|cron|定时|定期|daily|weekly|hourly/i.test(text)) {
      return 'cron';
    }
    if (/当.*时|if.*then|阈值|threshold|超过|低于/i.test(text)) {
      return 'threshold';
    }
    if (/事件|event|触发|trigger|webhook/i.test(text)) {
      return 'event';
    }
    if (/手动|manual/i.test(text)) {
      return 'manual';
    }
    return null;
  }

  /**
   * Validates a StandingOrderDraft for completeness and correctness.
   */
  validateDraft(draft: StandingOrderDraft): { valid: boolean; errors: string[] } {
    const errors: string[] = [];

    if (!draft.name) {
      errors.push('Name is required');
    }
    if (!draft.trigger?.type) {
      errors.push('Trigger type is required');
    }
    if (
      draft.trigger?.type === 'cron' &&
      !this.isValidCron(draft.trigger.cronExpression)
    ) {
      errors.push('Invalid cron expression');
    }
    if (!draft.agentInstructions?.prompt) {
      errors.push('Agent instruction is required');
    }

    return { valid: errors.length === 0, errors };
  }

  private isValidCron(expr?: string): boolean {
    if (!expr) return false;
    const parts = expr.trim().split(/\s+/);
    return parts.length === 5 || parts.length === 6;
  }
}
