package dev.sonpx.loyalty.agent.core.workflow;

import dev.sonpx.loyalty.agent.core.classifier.Intent;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Tracks the state of a multi-turn conversation workflow (e.g., creating a campaign or rule).
 * Stored per-session to maintain context across user turns.
 *
 * Workflow lifecycle: INIT → COLLECTING → CONFIRMING → COMPLETED / CANCELLED
 */
@Slf4j
@Getter
@Setter
public class WorkflowState {

    public enum Phase {
        /** Initial phase — asking for basic info */
        BASIC_INFO,
        /** Collecting reward/formula configuration (rule only) */
        REWARD_CONFIG,
        /** Showing summary and asking for confirmation */
        CONFIRMING,
        /** Workflow completed, data created */
        COMPLETED,
        /** User cancelled the workflow */
        CANCELLED
    }

    private final Intent workflowType;
    private Phase currentPhase;
    private final Map<String, Object> collectedData;
    private String lastQuestion;
    private boolean executing;

    public WorkflowState(Intent workflowType) {
        this.workflowType = workflowType;
        this.currentPhase = Phase.BASIC_INFO;
        this.collectedData = new LinkedHashMap<>();
    }

    public void putData(String key, Object value) {
        collectedData.put(key, value);
        log.debug("Workflow data collected: {} = {}", key, value);
    }

    public void putAllData(Map<String, Object> data) {
        if (data == null || data.isEmpty()) {
            return;
        }
        data.forEach(this::putData);
    }

    public Object getData(String key) {
        return collectedData.get(key);
    }

    public boolean hasData(String key) {
        return collectedData.containsKey(key) && collectedData.get(key) != null;
    }

    public boolean isActive() {
        return executing || (currentPhase != Phase.COMPLETED && currentPhase != Phase.CANCELLED);
    }

    public void startExecuting() {
        this.executing = true;
        log.info("Workflow execution started");
    }

    public void complete() {
        this.executing = false;
        this.currentPhase = Phase.COMPLETED;
        log.info("Workflow completed");
    }

    public void failExecution() {
        this.executing = false;
        log.info("Workflow execution failed; keeping workflow active for retry");
    }

    public void advancePhase() {
        switch (currentPhase) {
            case BASIC_INFO -> currentPhase = (workflowType == Intent.RULE_CREATE)
                    ? Phase.REWARD_CONFIG
                    : Phase.CONFIRMING;
            case REWARD_CONFIG -> currentPhase = Phase.CONFIRMING;
            case CONFIRMING -> currentPhase = Phase.COMPLETED;
            default -> { /* no-op */ }
        }
        log.info("Workflow advanced to phase: {}", currentPhase);
    }

    public void cancel() {
        this.currentPhase = Phase.CANCELLED;
        log.info("Workflow cancelled");
    }

    /**
     * Build a summary of all collected data for confirmation display.
     */
    public String buildSummary() {
        StringBuilder sb = new StringBuilder();
        sb.append("**Thông tin đã thu thập:**\n");
        for (Map.Entry<String, Object> entry : collectedData.entrySet()) {
            sb.append("- ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
        }
        return sb.toString();
    }
}
