///|
fn main {
  let args = @env.args()
  if args.length() >= 2 && args[1] == "oracle-check" {
    let oracle = parse_text_option(args, "--oracle", default="")
    match oracle {
      "provider-handoff-manifest" => run_provider_handoff_manifest_oracle(args)
      _ => println("oracle_check=FAIL reason=unknown-oracle oracle=\{oracle}")
    }
    return
  }
  if args.length() >= 2 && args[1] == "harness-handoffs" {
    let provider = parse_text_option(args, "--provider", default="all")
    for line in provider_handoff_lines(provider) {
      println(line)
    }
    return
  }
  if args.length() >= 2 && args[1] == "harness-coverage" {
    for line in provider_live_cli_coverage_lines() {
      println(line)
    }
    return
  }
  if args.length() >= 2 && args[1] == "harness-run-plan" {
    let provider = parse_text_option(args, "--provider", default="")
    let handoff = parse_text_option(
      args,
      "--handoff",
      default=parse_text_option(args, "--command", default=""),
    )
    let target = parse_text_option(args, "--target", default="windows-npcap")
    let iface = parse_text_option(
      args,
      "--interface",
      default=parse_text_option(args, "--iface", default=""),
    )
    let confirm = parse_text_option(
      args,
      "--confirm-interface",
      default=parse_text_option(args, "--confirm", default=""),
    )
    let artifact_dir = parse_text_option(
      args,
      "--artifact-dir",
      default="_build/provider-harness-live",
    )
    let allow_live = has_flag(args, "--allow-live") ||
      has_flag(args, "--allow-live-execution")
    for
      line in provider_harness_run_plan_lines(
        provider, handoff, target, iface, allow_live, confirm, artifact_dir,
      ) {
      println(line)
    }
    return
  }
  if args.length() >= 2 && args[1] == "harness-exec" {
    let provider = parse_text_option(args, "--provider", default="")
    let handoff = parse_text_option(
      args,
      "--handoff",
      default=parse_text_option(args, "--command", default=""),
    )
    let target = parse_text_option(args, "--target", default="windows-npcap")
    let iface = parse_text_option(
      args,
      "--interface",
      default=parse_text_option(args, "--iface", default=""),
    )
    let confirm = parse_text_option(
      args,
      "--confirm-interface",
      default=parse_text_option(args, "--confirm", default=""),
    )
    let artifact_dir = parse_text_option(
      args,
      "--artifact-dir",
      default="_build/provider-harness-live",
    )
    let allow_live = has_flag(args, "--allow-live") ||
      has_flag(args, "--allow-live-execution")
    for
      line in provider_harness_run_command_lines(
        provider,
        handoff,
        target,
        iface,
        allow_live,
        confirm,
        artifact_dir,
        parse_repeated_text_option(args, "--provider-arg"),
      ) {
      println(line)
    }
    return
  }
  print_help()
}

///|
pub fn provider_live_cli_coverage_lines() -> Array[String] {
  let cases = @evidence.provider_live_cli_coverage_cases()
  let report = @evidence.provider_live_cli_coverage_report(cases)
  let status = if report.passes() { "pass" } else { "failed" }
  let lines : Array[String] = [
    "schema=\{report.schema} status=\{status} case_count=\{report.case_count} expected_case_count=\{report.expected_case_count} provider_count=\{report.provider_count} target_count=\{report.target_count} handoff_count=\{report.handoff_count}",
    "families ethercat=\{report.ethercat_case_count} profinet_dcp=\{report.profinet_dcp_case_count} profinet_helper=\{report.profinet_helper_case_count} profinet_rt_pcap=\{report.profinet_rt_pcap_case_count} profinet_root_facade=\{report.profinet_root_facade_case_count}",
    "readiness dry_run_ready=\{report.dry_run_ready_count} live_command_ready=\{report.live_command_ready_count} windows_live_ready=\{report.windows_live_ready_count} linux_live_ready=\{report.linux_live_ready_count} blocked_provider_cli_unavailable=\{report.blocked_provider_cli_unavailable_count} blocked_missing_provider_args=\{report.blocked_missing_provider_args_count}",
    "boundary may_open_device_when_run=\{report.may_open_device_when_run_count} executes_live_io_now=\{report.executes_live_io_now_count} external_runner_failures=\{report.external_runner_failure_count} protocol_stack_dependency_failures=\{report.protocol_stack_dependency_failure_count} provider_harness_boundary_failures=\{report.provider_harness_boundary_failure_count} live_evidence_claims=\{report.live_evidence_claim_count} replaces_shell_execution=\{bool_text(report.replaces_shell_execution)} live_io_evidence=\{bool_text(report.live_io_evidence)}",
  ]
  for case_ in cases {
    lines.push(provider_live_cli_coverage_case_line(case_))
  }
  lines
}

///|
pub fn provider_handoff_lines(provider : String) -> Array[String] {
  let lines : Array[String] = []
  if provider == "all" || provider == "moonecat" {
    append_moonecat_handoffs(lines)
  }
  if provider == "all" || provider == "profinet" {
    append_profinet_handoffs(lines)
  }
  if lines.length() == 0 {
    lines.push(
      "error unknown-provider=\{provider} allowed=all|moonecat|profinet",
    )
  }
  lines
}

///|
pub fn provider_harness_run_plan_lines(
  provider : String,
  handoff : String,
  target : String,
  interface_name : String,
  allow_live_execution : Bool,
  confirm_interface_name : String,
  artifact_dir : String,
) -> Array[String] {
  let request = @evidence.provider_harness_live_run_request(
    provider, handoff, target, interface_name, allow_live_execution, confirm_interface_name,
    artifact_dir,
  )
  @evidence.provider_harness_live_run_plan_lines(
    @evidence.provider_harness_live_run_plan_report(request),
  )
}

///|
pub fn provider_harness_run_command_lines(
  provider : String,
  handoff : String,
  target : String,
  interface_name : String,
  allow_live_execution : Bool,
  confirm_interface_name : String,
  artifact_dir : String,
  provider_args : Array[String],
) -> Array[String] {
  let request = @evidence.provider_harness_live_run_request(
    provider, handoff, target, interface_name, allow_live_execution, confirm_interface_name,
    artifact_dir,
  )
  let plan = @evidence.provider_harness_live_run_plan_report(request)
  @evidence.provider_harness_live_execution_handoff_lines(
    @evidence.provider_harness_live_execution_handoff_report(
      plan, provider_args,
    ),
  )
}

///|
fn provider_live_cli_coverage_case_line(
  case_ : @evidence.ProviderLiveCliCoverageCase,
) -> String {
  let dry = provider_live_cli_coverage_handoff_report(case_, false)
  let live = provider_live_cli_coverage_handoff_report(case_, true)
  "case provider=\{case_.provider} command=\{case_.command} family=\{case_.family} target=\{case_.target} expected_cli_available=\{bool_text(case_.expected_cli_available)} provider_arg_count=\{case_.provider_args.length()} dry_status=\{dry.status} live_status=\{live.status} cli_package=\{live.provider_cli_package} interface_required=\{bool_text(live.provider_interface_required)} may_open_device_when_run=\{bool_text(live.may_open_device_when_run)} executes_live_io_now=\{bool_text(live.executes_live_io_now)} requires_external_runner=\{bool_text(live.requires_external_runner)} live_evidence_claim=\{bool_text(live.live_evidence_claim)} command_text=\{live.command_text}"
}

///|
fn provider_live_cli_coverage_handoff_report(
  case_ : @evidence.ProviderLiveCliCoverageCase,
  allow_live : Bool,
) -> @evidence.ProviderHarnessLiveExecutionHandoffReport {
  let iface = if allow_live {
    provider_live_cli_coverage_interface(case_.target)
  } else {
    ""
  }
  let plan = @evidence.provider_harness_live_run_plan_report(
    @evidence.provider_harness_live_run_request(
      case_.provider,
      case_.command,
      case_.target,
      iface,
      allow_live,
      iface,
      "_build/provider-live-cli-coverage",
    ),
  )
  @evidence.provider_harness_live_execution_handoff_report(
    plan,
    case_.provider_args,
  )
}

///|
fn provider_live_cli_coverage_interface(target : String) -> String {
  if target == "windows-npcap" {
    "\\Device\\NPF_{ISOCHRONON_TEST}"
  } else if target == "linux-raw" {
    "eth0"
  } else {
    ""
  }
}

///|
fn append_moonecat_handoffs(lines : Array[String]) -> Unit {
  let report = @moonecat.moonecat_live_command_ownership_report()
  lines.push(
    "provider=moonecat handoffs=\{report.handoff_count} live_default_open_allowed_count=\{report.live_default_open_allowed_count} lockwire_dependency_count=\{report.lockwire_dependency_in_moonecat_count} live_evidence_present=\{bool_text(report.live_evidence_present)}",
  )
  for handoff in @moonecat.moonecat_live_command_handoffs() {
    lines.push(
      "handoff provider=moonecat command=\{handoff.command} capability=\{handoff.capability} binding=\{handoff.required_binding_id} evidence=\{handoff.manual_evidence_slot} entry=\{handoff.provider_harness_entry}",
    )
  }
}

///|
fn append_profinet_handoffs(lines : Array[String]) -> Unit {
  let report = @profinet.profinet_lockwire_io_binding_report()
  lines.push(
    "provider=profinet bindings=\{report.binding_count} legacy_deletion_candidates=\{report.legacy_package_deletion_candidate_count} live_default_open_allowed_count=\{report.live_default_open_allowed_count} lockwire_dependency_count=\{report.direct_profinet_import_count} live_evidence_present=\{bool_text(report.live_evidence_present)}",
  )
  append_profinet_group(
    lines,
    "dcp",
    @profinet.profinet_dcp_live_command_handoffs(),
  )
  append_profinet_group(
    lines,
    "helper",
    @profinet.profinet_helper_live_command_handoffs(),
  )
  append_profinet_group(
    lines,
    "rt-pcap",
    @profinet.profinet_rt_pcap_live_command_handoffs(),
  )
  append_profinet_group(
    lines,
    "root-facade",
    @profinet.profinet_root_facade_native_handoffs(),
  )
}

///|
fn append_profinet_group(
  lines : Array[String],
  group : String,
  handoffs : ArrayView[@profinet.ProfinetLiveCommandHandoff],
) -> Unit {
  for handoff in handoffs {
    lines.push(
      "handoff provider=profinet group=\{group} command=\{handoff.command} capability=\{handoff.capability} binding=\{handoff.required_binding_id} evidence=\{handoff.manual_evidence_slot} entry=\{handoff.provider_harness_entry}",
    )
  }
}

///|
fn print_help() -> Unit {
  println("mokomoking2501/fieldbus_core provider harness")
  println("commands:")
  println("  - harness-handoffs [--provider all|moonecat|profinet]")
  println("  - harness-coverage")
  println(
    "  - harness-run-plan --provider moonecat|profinet --handoff  [--target windows-npcap|linux-raw] [--interface ] [--allow-live --confirm-interface ]",
  )
  println(
    "  - harness-exec --provider moonecat|profinet --handoff  [--target windows-npcap|linux-raw] [--interface ] [--allow-live --confirm-interface ] [--provider-arg  ...]",
  )
  println(
    "  - oracle-check --oracle provider-handoff-manifest --manifest-file  --facts-file ",
  )
  println(
    "default: no-live inventory/plan/command template only; does not open NIC",
  )
}

///|
fn parse_text_option(
  args : Array[String],
  name : String,
  default~ : String,
) -> String {
  for i in 0.. Bool {
  args.any(fn(arg) { arg == name })
}

///|
fn parse_repeated_text_option(
  args : Array[String],
  name : String,
) -> Array[String] {
  let values : Array[String] = []
  for i in 0.. String {
  if value {
    "true"
  } else {
    "false"
  }
}

///|
/// D77b provider-handoff-manifest oracle-check dispatch.
///
/// The thin ps1 wrapper keeps only external actions (run the manifest
/// generator, read the referenced stdout/stderr/commands-text/artifact files,
/// compute their SHA256/bytes/lines) and writes a facts JSON; this entry reads
/// the manifest + facts, derives the digest facts, and applies the three MoonBit
/// oracles owned by `fieldbus_core/provider_handoff_evidence`. Hosting this here
/// rather than in lockwire/test/cmd/main keeps lockwire from importing
/// fieldbus_core (which would invert the dependency boundary).
fn run_provider_handoff_manifest_oracle(args : Array[String]) -> Unit {
  let manifest_file = parse_text_option(args, "--manifest-file", default="")
  if manifest_file == "" {
    println(
      "oracle_check=FAIL reason=missing-manifest-file oracle=provider-handoff-manifest",
    )
    return
  }
  let manifest_text = @fs.read_file_to_string(manifest_file) catch {
    _ =>
      return println(
        "oracle_check=FAIL reason=read-failed oracle=provider-handoff-manifest file=\{manifest_file}",
      )
  }
  let facts_file = parse_text_option(args, "--facts-file", default="")
  if facts_file == "" {
    println(
      "oracle_check=FAIL reason=missing-facts-file oracle=provider-handoff-manifest",
    )
    return
  }
  let facts_text = @fs.read_file_to_string(facts_file) catch {
    _ =>
      return println(
        "oracle_check=FAIL reason=read-failed oracle=provider-handoff-manifest file=\{facts_file}",
      )
  }
  let file_facts = @evidence.provider_handoff_manifest_file_facts_from_json(
    facts_text,
  )
  let digest_facts : @evidence.ProviderHandoffManifestDigestFacts = {
    stdout_sha256: file_facts.stdout_fact.sha256,
    commands_text_sha256: file_facts.commands_text_fact.sha256,
  }
  let policy_report = @evidence.provider_handoff_manifest_policy_report_from_json(
    manifest_text,
  )
  let digest_report = @evidence.provider_handoff_manifest_digest_fact_policy_report_from_json(
    manifest_text, digest_facts,
  )
  let file_report = @evidence.provider_handoff_manifest_file_fact_policy_report_from_json(
    manifest_text, file_facts,
  )
  let passes = policy_report.passes() &&
    digest_report.passes() &&
    file_report.passes()
  let status = if passes { "PASS" } else { "FAIL" }
  println(
    "oracle_check=\{status} oracle=provider-handoff-manifest schema=\{@evidence.provider_handoff_manifest_schema()}",
  )
  println(
    "provider_count=\{policy_report.provider_count} handoff_count=\{policy_report.handoff_count} evidence_slot_count=\{policy_report.evidence_slot_count}",
  )
  println(
    "policy_pass=\{policy_report.passes()} digest_fact_pass=\{digest_report.passes()} file_fact_pass=\{file_report.passes()} parse_error_count=\{policy_report.parse_error_count}",
  )
  println(
    "provider_policy_failure_count=\{policy_report.provider_policy_failure_count} handoff_policy_failure_count=\{policy_report.handoff_policy_failure_count} provider_name_coverage_count=\{policy_report.provider_name_coverage_count}",
  )
  println(
    "digest_source_shape_failure_count=\{digest_report.digest_source_shape_failure_count} digest_source_mismatch_count=\{digest_report.digest_source_mismatch_count} cross_file_fact_mismatch_count=\{digest_report.cross_file_fact_mismatch_count}",
  )
  println(
    "commands_text_file_fact_mismatch_count=\{file_report.commands_text_file_fact_mismatch_count} command_stream_fact_mismatch_count=\{file_report.command_stream_fact_mismatch_count} stdout_line_mismatch_count=\{file_report.stdout_line_mismatch_count} artifact_file_fact_mismatch_count=\{file_report.artifact_file_fact_mismatch_count}",
  )
  if !passes {
    @sys.exit(1)
  }
}