package com.correx.infrastructure.tools.task

import com.correx.core.approvals.Tier
import com.correx.core.events.events.ToolRequest
import com.correx.core.events.types.TaskId
import com.correx.core.tasks.TaskService
import com.correx.core.tools.contract.Tool
import com.correx.core.tools.contract.ToolCapability
import com.correx.core.tools.contract.ToolExecutor
import com.correx.core.tools.contract.ToolResult
import com.correx.core.tools.contract.ValidationResult
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject

/**
 * Agent-facing tool: soft-delete a task (tombstone). History is preserved in the event log;
 * the task drops out of active views. Use 'task_update' with action=cancel to record an
 * abandoned-but-visible outcome instead.
 */
class TaskDeleteTool(private val service: TaskService) : Tool, ToolExecutor {

    override val name: String = "task_delete"
    override val description: String =
        "Use only to remove a task opened by mistake or a duplicate: soft-deletes it (drops " +
            "from active views; history is kept). For real work that's been abandoned, use " +
            "task_update action=cancel instead so it stays visible."
    override val parametersSchema: JsonObject = buildJsonObject {
        put("type", "object")
        putJsonObject("properties") {
            putJsonObject("id") { put("type", "string"); put("description", "Task id, e.g. 'auth-142'.") }
        }
        put("required", buildJsonArray { add(JsonPrimitive("id")) })
    }
    override val tier: Tier = Tier.T2
    override val requiredCapabilities: Set<ToolCapability> = emptySet()

    override fun validateRequest(request: ToolRequest): ValidationResult {
        request.stringParam("id") ?: return ValidationResult.Invalid("Missing 'id' (string).")
        return ValidationResult.Valid
    }

    override suspend fun execute(request: ToolRequest): ToolResult {
        val id = request.stringParam("id")
            ?: return ToolResult.Failure(request.invocationId, "Missing 'id' (string).", recoverable = false)
        return if (service.delete(TaskId(id))) {
            ToolResult.Success(request.invocationId, output = "Deleted $id", metadata = mapOf("taskId" to id))
        } else {
            ToolResult.Failure(request.invocationId, "No such task: $id", recoverable = false)
        }
    }
}
