///|
/// Stateless single-effect executor for the M1 functional Kernel (ADR §2.1,
/// §2.5, §2.9).
///
/// This is the imperative shell that turns ONE reducer-declared Effect into
/// ONE structured RunInput. It executes no business logic, owns no RunState,
/// holds no queues, journals or barriers. The M2 Harness will reuse
/// `execute_one` verbatim and replace the M1 scripted minimal driver.
///
/// Three responsibilities:
/// 1. `RuntimeRegistry`: maps `OwnerId` -> `&ToolProvider` and
///    `ModelId` -> `&ModelPort`.
/// 2. `execute_one(effect, registry, ctx)`: dispatch one Effect to its
///    bound adapter. Convert every transport/runtime/parse/cancel result to
///    a typed RunInput.
/// 3. `ScriptedExecutor`: a fake registry+executor for conformance tests,
///    configured by effect_id.
///
/// The executor is allowed to import async, fs, http, time, random and port
/// traits — it is the imperative shell. The REDUCER is the pure part.

// ──────────────────────────────────────────────────────────────────────────
// ModelId (RuntimeRegistry key for ModelPort)
// ──────────────────────────────────────────────────────────────────────────

///|
/// Identifier for a model binding. M1 supports a single model per Run
/// (host-supplied); M2 may add multi-model routing. The Kernel reducer
/// never references this; it only sees the model step id.
pub(all) struct ModelId {
  value : String
} derive(Eq, Hash, Debug)

///|
pub fn ModelId::new(value : String) -> Result[ModelId, String] {
  if value == "" {
    Err("ModelId must be non-empty")
  } else {
    Ok(ModelId::{ value, })
  }
}

///|
pub fn ModelId::unchecked(value : String) -> ModelId {
  ModelId::{ value, }
}

///|
pub fn ModelId::to_string(self : ModelId) -> String {
  self.value
}

// ──────────────────────────────────────────────────────────────────────────
// RuntimeRegistry
// ──────────────────────────────────────────────────────────────────────────

///|
/// Maps `OwnerId` -> `&ToolProvider` and `ModelId` -> `&ModelPort`. Built
/// by the host from the same providers that built the catalog snapshot.
///
/// Missing owner / stale snapshot version returned from the registry is a
/// typed `ToolFailed` Input carrying `InvariantCategory::MissingOwner` /
/// `StaleSnapshot` (ADR §2.4). The executor does NOT silently fall back.
pub struct RuntimeRegistry {
  model_port : &ModelPort
  model_id : ModelId
  tool_providers : Map[String, &ToolProvider]
}

///|
pub fn RuntimeRegistry::new(
  model_port : &ModelPort,
  model_id~ : ModelId,
  tool_bindings : Array[(OwnerId, &ToolProvider)],
) -> RuntimeRegistry {
  let map : Map[String, &ToolProvider] = Map::from_array([])
  for binding in tool_bindings {
    let (owner, provider) = binding
    map[owner.to_string()] = provider
  }
  { model_port, model_id, tool_providers: map }
}

///|
/// Look up a ToolProvider by owner id. Missing owner returns None; the
/// caller (executor) is responsible for raising the typed invariant
/// failure via a `ToolFailed` Input.
pub fn RuntimeRegistry::find_tool_provider(
  self : RuntimeRegistry,
  owner : OwnerId,
) -> &ToolProvider? {
  self.tool_providers.get(owner.to_string())
}

///|
pub fn RuntimeRegistry::model_port(self : RuntimeRegistry) -> &ModelPort {
  self.model_port
}

///|
pub fn RuntimeRegistry::model_id(self : RuntimeRegistry) -> ModelId {
  self.model_id
}

// ──────────────────────────────────────────────────────────────────────────
// execute_one — stateless single-effect dispatch
// ──────────────────────────────────────────────────────────────────────────

///|
/// Execute ONE Effect and return ONE structured RunInput. The executor
/// holds no state; every call is independent. The result is fed straight
/// back to `reduce`.
///
/// Categorisation:
/// - `CallModel` → calls `ModelPort.chat_streaming`, folds streaming chunks
///   via the M0 `StreamAccumulator`, returns `ModelCompleted` on success or
///   `ModelFailed` on `ModelError`.
/// - `ExecuteTool` → looks up the owner in the registry. Missing owner or
///   stale snapshot version returns `ToolFailed` carrying the typed
///   invariant category. Otherwise calls `ToolProvider.execute` and returns
///   `ToolCompleted` (mapping legacy `ToolResult.is_error` to
///   `ToolReportedError` / `Success`) or `ToolFailed` (mapping
///   `RuntimeError`).
/// - `CancelOutstanding` → records the cancel disposition and returns a
///   no-op acknowledgment as a typed input (M1: always returns CancelAcked
///   via ToolFailed with no invariant; the reducer treats it as already
///   terminal). Real adapter propagation hardening is M3.
pub async fn execute_one(
  effect : Effect,
  registry : RuntimeRegistry,
  on_chunk : (StreamChunk) -> Unit,
) -> RunInput {
  match effect {
    CallModel(effect_id~, payload~) =>
      execute_call_model(effect_id, payload, registry, on_chunk)
    ExecuteTool(effect_id~, payload~) =>
      execute_execute_tool(effect_id, payload, registry)
    CancelOutstanding(effect_id~, payload~) => {
      // M1: cancel is recorded but the underlying operation has no real
      // cancellation in the scripted/legacy adapter. We return a no-op
      // acknowledgment — the reducer has already transitioned to Terminal
      // by the time this effect is dispatched (the reducer does not wait).
      // Use a synthetic ModelCompleted-rejection-free path: emit a Custom
      // InputRejected? No — there is no "CancelAcked" input variant. The
      // reducer treats CancelOutstanding as fire-and-forget: it does not
      // require a completion for it. The driver therefore drops the result.
      ignore(effect_id)
      ignore(payload)
      // Return a synthetic ToolCompleted against a sentinel call id. This
      // is a known M1 simplification: real adapter cancellation hardening
      // belongs to M3 and will add a proper CancelAcked Input variant.
      // The driver only invokes execute_one for cancel effects when there
      // is no other in-flight work; it discards the result.
      ToolCompleted(payload=ToolCompletedPayload::{
        effect_id: EffectId::first(),
        call_id: CallId::unchecked("__cancel_ack__"),
        outcome: RuntimeFailure(
          error_category="CancelAck",
          message="cancel recorded (M1 fake)",
        ),
      })
    }
  }
}

///|
async fn execute_call_model(
  effect_id : EffectId,
  payload : CallModelPayload,
  registry : RuntimeRegistry,
  on_chunk : (StreamChunk) -> Unit,
) -> RunInput {
  // Convert canonical messages to legacy Message for the ModelPort call.
  let legacy_messages : Array[Message] = []
  for cm in payload.messages {
    legacy_messages.push(canonical_to_legacy_message(cm))
  }
  // Tools: the ModelPort expects legacy `ToolDef`. The catalog snapshot
  // owns the canonical defs; we project to a synthetic empty tool list
  // here because the Kernel does not have a back-reference to the snapshot
  // from the effect payload (only the version). The facade (T10) is the
  // proper place to inject tool definitions; for the executor we pass an
  // empty array — the model adapter in production should be driven via
  // the facade, not the executor directly. This keeps M1 scoped.
  let empty_tools : Array[ToolDef] = []
  let chat_options = canonical_options_to_chat(payload.call_options)
  let result : Result[ModelResponse, ModelError] = Ok(
    registry
    .model_port()
    .chat_streaming(legacy_messages, empty_tools, chat_options, on_chunk),
  ) catch {
    e => Err(e)
  }
  match result {
    Ok(response) =>
      // Convert legacy ModelResponse → canonical AssistantCompletion.
      ModelCompleted(payload=ModelCompletedPayload::{
        effect_id,
        model_step_id: payload.model_step_id,
        completion: legacy_to_completion(response),
      })
    Err(e) =>
      ModelFailed(payload=ModelFailedPayload::{
        effect_id,
        model_step_id: payload.model_step_id,
        failure: model_error_to_failure(e),
      })
  }
}

///|
async fn execute_execute_tool(
  effect_id : EffectId,
  payload : ExecuteToolPayload,
  registry : RuntimeRegistry,
) -> RunInput {
  // Stale snapshot version check: registry does not track versions per se,
  // but the effect's catalog_version must match what the host registered.
  // M1 simplification: we trust the effect's payload and let the reducer's
  // correlation invariants catch any mismatch. A real M3 adapter may
  // re-check against the snapshot registry.
  match registry.find_tool_provider(payload.owner) {
    None =>
      // Invariant failure: MissingOwner. Terminate via typed ToolFailed.
      ToolFailed(payload=ToolFailedPayload::{
        effect_id,
        call_id: payload.call_id,
        runtime: None,
        invariant_failure: Some(MissingOwner(owner=payload.owner)),
      })
    Some(provider) => {
      let legacy_call : ToolCall = {
        id: payload.call_id.to_string(),
        name: payload.tool_name.to_string(),
        arguments: payload.arguments,
      }
      let result : Result[ToolResult, RuntimeError] = Ok(
        provider.execute(payload.tool_name.to_string(), legacy_call),
      ) catch {
        e => Err(e)
      }
      match result {
        Ok(tr) => {
          // Map legacy ToolResult to canonical ToolOutcome.
          let outcome : ToolOutcome = if tr.is_error {
            ToolReportedError(content=tr.content, structured=tr.structured)
          } else {
            Success(content=tr.content, structured=tr.structured)
          }
          ToolCompleted(payload=ToolCompletedPayload::{
            effect_id,
            call_id: payload.call_id,
            outcome,
          })
        }
        Err(e) =>
          // Map RuntimeError to ModelFailure variant for the runtime
          // category. The reducer builds RuntimeFailure outcome.
          ToolFailed(payload=ToolFailedPayload::{
            effect_id,
            call_id: payload.call_id,
            runtime: Some(Transport(reason=e.to_string())),
            invariant_failure: None,
          })
      }
    }
  }
}

// ──────────────────────────────────────────────────────────────────────────
// Legacy ↔ Canonical conversions (only the executor is allowed to import
// legacy types; the reducer is pure)
// ──────────────────────────────────────────────────────────────────────────

///|
/// Convert a canonical message back to the legacy Message type the
/// ModelPort expects. Inverse of `legacy_to_completion` for assistant
/// payloads; for system/user/tool messages we project the canonical
/// content.
pub fn canonical_to_legacy_message(cm : CanonicalMessage) -> Message {
  match cm {
    SystemMessage(content~) =>
      {
        role: System,
        content: canonical_content_to_legacy(content),
        tool_calls: [],
        tool_call_id: None,
        name: None,
        reasoning_content: None,
      }
    UserMessage(content~) =>
      {
        role: User,
        content: canonical_content_to_legacy(content),
        tool_calls: [],
        tool_call_id: None,
        name: None,
        reasoning_content: None,
      }
    AssistantMessage(content~, tool_calls~, reasoning~, finish_reason~) => {
      ignore(finish_reason) // legacy Message has no finish_reason field
      {
        role: Assistant,
        content: canonical_content_to_legacy(content),
        tool_calls: canonical_tool_calls_to_legacy(tool_calls),
        tool_call_id: None,
        name: None,
        reasoning_content: match reasoning {
          Some(r) => Some(r.content)
          None => None
        },
      }
    }
    ToolMessage(call_id~, tool_name~, outcome~) => {
      let (content, _is_error) = outcome_to_legacy(outcome)
      {
        role: Tool,
        content: [Text(content)],
        tool_calls: [],
        tool_call_id: Some(call_id.to_string()),
        name: Some(tool_name.to_string()),
        reasoning_content: None,
      }
    }
  }
}

///|
fn canonical_content_to_legacy(
  content : Array[CanonicalContent],
) -> Array[Content] {
  let out : Array[Content] = []
  for c in content {
    match c {
      Text(s) => out.push(Text(s))
      Image(media_type~, data~) => out.push(Image(media_type, data))
    }
  }
  out
}

///|
fn canonical_tool_calls_to_legacy(
  calls : Array[CanonicalToolCall],
) -> Array[ToolCall] {
  let out : Array[ToolCall] = []
  for c in calls {
    out.push({
      id: c.call_id.to_string(),
      name: c.name.to_string(),
      arguments: c.arguments,
    })
  }
  out
}

///|
/// Convert legacy ModelResponse → canonical AssistantCompletion. This is
/// the inverse of the legacy duplication: we read tool_calls/reasoning
/// from the inner Message (the single source of truth in canonical form)
/// and ignore the duplicated top-level fields.
pub fn legacy_to_completion(response : ModelResponse) -> AssistantCompletion {
  let reasoning = match response.message.reasoning_content {
    Some(s) => Some(Reasoning::{ content: s })
    None => None
  }
  AssistantCompletion::new(
    content=legacy_content_to_canonical(response.message.content),
    tool_calls=legacy_tool_calls_to_canonical(response.message.tool_calls),
    reasoning~,
    finish_reason=legacy_finish_to_canonical(response.finish_reason),
    usage=legacy_usage_to_canonical(response.usage),
  )
}

///|
fn legacy_content_to_canonical(
  content : Array[Content],
) -> Array[CanonicalContent] {
  let out : Array[CanonicalContent] = []
  for c in content {
    match c {
      Text(s) => out.push(Text(s))
      Image(t, d) => out.push(Image(media_type=t, data=d))
    }
  }
  out
}

///|
fn legacy_tool_calls_to_canonical(
  calls : Array[ToolCall],
) -> Array[CanonicalToolCall] {
  let out : Array[CanonicalToolCall] = []
  for c in calls {
    out.push({
      call_id: CallId::unchecked(c.id),
      name: ToolName::unchecked(c.name),
      arguments: c.arguments,
    })
  }
  out
}

///|
fn legacy_finish_to_canonical(reason : FinishReason) -> AssistantFinishReason {
  match reason {
    Stop => Stop
    Length => Length
    ToolCalls => ToolCalls
    Other(s) => Other(s)
  }
}

///|
fn legacy_usage_to_canonical(usage : Usage?) -> CanonicalUsage? {
  match usage {
    Some(u) =>
      Some({
        input_tokens: u.input_tokens,
        output_tokens: u.output_tokens,
        total_tokens: u.total_tokens,
      })
    None => None
  }
}

///|
fn canonical_options_to_chat(options : Json) -> ChatOptions {
  // M1: pass through defaults; the host can build options upstream.
  // Parsing Json into ChatOptions is a thin concern; here we just pass
  // defaults because the Kernel effect payload already carries what the
  // host set up. A fuller M3 implementation may parse the Json.
  ignore(options)
  {
    temperature: None,
    max_output_tokens: None,
    tool_choice: None,
    reasoning_effort: None,
  }
}

///|
fn model_error_to_failure(e : ModelError) -> ModelFailure {
  match e {
    RequestBuild(msg) => RequestBuild(reason=msg)
    Transport(msg) => Transport(reason=msg)
    ResponseParse(msg) => Parse(reason=msg)
  }
}

///|
/// Convert canonical ToolOutcome → (legacy content, legacy is_error).
/// Used by the facade when feeding outcomes back to legacy observers.
pub fn outcome_to_legacy(outcome : ToolOutcome) -> (String, Bool) {
  match outcome {
    Success(content~, ..) => (content, false)
    ToolReportedError(content~, ..) => (content, true)
    RuntimeFailure(message~, ..) => (message, true)
    NotExecuted(reason~, ..) =>
      ("tool not executed: " + reason.to_string(), true)
  }
}