package control

func deriveClose(closeRun *CloseRun) {
	if closeRun.DefinitionHash != "" && closeRun.DefinitionHash != DefinitionHash() {
		closeRun.Status = "blocked"
		for _, step := range closeRun.Steps {
			step.Action = StepAction{Type: "inspect", Label: "查看历史定义", ReadOnly: true, Reason: "定义版本已变化；历史结果不能套用新 DAG，请建立新版本账期"}
		}
		return
	}
	allPassed := true
	hasRunning := false
	hasBlocker := false

	for _, definition := range MonthlyCloudClose {
		step := closeRun.Steps[definition.Key]
		if step == nil {
			step = &StepState{Key: definition.Key, Execution: ExecutionPending, Verification: VerificationNotChecked, Receipt: map[string]any{}}
			closeRun.Steps[definition.Key] = step
		}
		step.Definition = definition
		step.BlockedBy = step.BlockedBy[:0]
		for _, dependency := range definition.DependsOn {
			upstream := closeRun.Steps[dependency]
			if upstream == nil || upstream.Verification != VerificationPassed {
				step.BlockedBy = append(step.BlockedBy, dependency)
			}
		}

		step.Action = deriveAction(step)
		if step.Execution == ExecutionRunning {
			hasRunning = true
		}
		if step.Execution == ExecutionFailed || step.Execution == ExecutionUnknown || step.Verification == VerificationFailed {
			hasBlocker = true
		}
		if step.Verification != VerificationPassed {
			allPassed = false
		}
	}

	switch {
	case allPassed:
		closeRun.Status = "completed"
	case hasBlocker:
		closeRun.Status = "blocked"
	case hasRunning:
		closeRun.Status = "running"
	default:
		closeRun.Status = "ready"
	}
}

func deriveAction(step *StepState) StepAction {
	if step.Verification == VerificationPassed {
		return StepAction{Type: "inspect", Label: "查看回执", Enabled: true, ReadOnly: true}
	}
	if step.Execution == ExecutionRunning {
		return StepAction{Type: "inspect", Label: "运行中", Enabled: false, ReadOnly: true, Reason: "当前 attempt 尚未终态"}
	}
	if step.Execution == ExecutionUnknown {
		return StepAction{Type: "reconcile", Label: "对账状态", Enabled: true, ReadOnly: true}
	}
	if step.Execution == ExecutionSucceeded && step.Verification != VerificationPassed {
		return StepAction{Type: "verify", Label: "等待独立验证", Enabled: false, ReadOnly: true, Reason: "执行成功不代表产出已通过验证"}
	}
	if len(step.BlockedBy) > 0 {
		return StepAction{Type: "run", Label: "等待上游", Enabled: false, Reason: "前置步骤尚未验证"}
	}
	if step.Execution == ExecutionFailed || step.Verification == VerificationFailed {
		return StepAction{Type: "retry", Label: "重试此步", Enabled: true}
	}
	if step.Definition.Kind == Barrier {
		return StepAction{Type: "verify", Label: "重新检查", Enabled: true, ReadOnly: true}
	}
	return StepAction{Type: "run", Label: "运行此步", Enabled: true}
}
