package com.correx.apps.server.protocol

import com.correx.core.events.risk.RiskSignal
import com.correx.core.events.risk.RiskSummary
import kotlinx.serialization.Serializable

@Serializable
data class RiskSummaryDto(
    val level: String,
    val factors: List<String>,
    val recommendedAction: String,
    val rationale: List<String> = emptyList(),
)

@Serializable
data class AssessedIssueDto(
    val code: String,
    val message: String,
    val severity: String,
)

@Serializable
data class ProviderHealthDto(
    val providerId: String,
    val status: String,
    val loadPercent: Int?,
)

@Serializable
data class SessionConfigDto(
    val timeoutMs: Long?,
    val retryPolicy: String?,
)

@Serializable
data class SessionStateDto(
    val status: String,
    val currentStageId: String?,
    val pauseReason: String?,
)

@Serializable
data class ApprovalDto(
    val requestId: String,
    val tier: String,
    val toolName: String? = null,
    val preview: String? = null,
)

@Serializable
enum class PauseReason {
    APPROVAL_PENDING,
    USER_REQUESTED,
}

@Serializable
data class StageToolDecl(
    val stageId: String,
    val tools: List<ToolDecl>,
)

@Serializable
data class ToolDecl(
    val name: String,
    val tier: Int,
)

@Serializable
data class EventEntryDto(
    val timestamp: Long,
    val type: String,
    val detail: String,
)

@Serializable
data class ToolRecordDto(
    val name: String,
    val tier: Int,
    val status: String,
    val diff: String? = null,
)

@Serializable
data class WorkflowDto(
    val workflowId: String,
    val description: String,
)

internal fun RiskSummary.toDto(): RiskSummaryDto = RiskSummaryDto(
    level = level.name,
    factors = signals.map { signal ->
        when (signal) {
            is RiskSignal.CycleWithoutExit -> "Cycle without exit: ${signal.cycleId}"
            is RiskSignal.RepeatedFailure -> "Repeated failure: ${signal.reason} (${signal.count}×)"
            is RiskSignal.ValidationErrors -> "Validation errors: ${signal.errorCount}"
            is RiskSignal.InferenceTimeout -> "Inference timeout: ${signal.elapsedMs}ms"
        }
    },
    recommendedAction = recommendedAction.name,
    rationale = rationale,
)
