///|
pub(all) enum Access {
  Exists
  Read
  Write
  Execute
}

///|
pub(all) enum PathKind {
  RegularFile
  Directory
}

///|
pub(all) enum Probe {
  File(String, Access)
  TypedFile(String, Access, PathKind)
  Tool(String, String)
  Dns(String)
  Tcp(String, Int32)
  Resource(String, Int64)
  DiskAt(String, Int64)
}

///|
/// Implementations must confine file access, bound I/O, and avoid shell evaluation.
pub(open) trait Platform {
  fn facts(Self) -> Map[String, String]
  async fn inspect(Self, Probe) -> Finding
  async fn read_text(Self, String, Int32) -> String
}

///|
/// Build a host-backed rule. Network probes are opt-in on every run.
pub fn platform_check(
  id : String,
  category : String,
  platform : &Platform,
  probe : Probe,
  timeout_ms~ : Int32 = 3000,
) -> Rule {
  rule(
    id,
    category,
    ctx => {
      match probe {
        Dns(_) | Tcp(_, _) =>
          if !ctx.allow_network {
            return finding(
              Skipped,
              "network_disabled",
              "Network probing requires explicit opt-in",
            )
          }
        _ => ()
      }
      platform.inspect(probe)
    },
    timeout_ms~,
  )
}

///|
/// The mock does no I/O. Keys identify probes using `probe_key`.
pub struct MockPlatform {
  snapshot : Map[String, String]
  observations : Map[String, Finding]
  files : Map[String, String]
}

///|
pub fn MockPlatform::new(
  facts~ : Map[String, String] = Map([]),
  observations~ : Map[String, Finding] = Map([]),
  files~ : Map[String, String] = Map([]),
) -> MockPlatform {
  {
    snapshot: facts.copy(),
    observations: observations.copy(),
    files: files.copy(),
  }
}

///|
pub fn probe_key(probe : Probe) -> String {
  match probe {
    File(path, access) => {
      let mode = match access {
        Exists => "exists:"
        Read => "read:"
        Write => "write:"
        Execute => "execute:"
      }
      "file:" + mode + path
    }
    TypedFile(path, access, kind) =>
      probe_key(File(path, access)) +
      (if kind is Directory { ":directory" } else { ":file" })
    DiskAt(path, minimum) => "disk:\{path}:\{minimum}"
    Tool(name, constraint) => "tool:\{name}:\{constraint}"
    Dns(host) => "dns:\{host}"
    Tcp(host, port) => "tcp:\{host}:\{port}"
    Resource(name, minimum) => "resource:\{name}:\{minimum}"
  }
}

///|
pub impl Platform for MockPlatform with fn facts(self) {
  self.snapshot.copy()
}

///|
pub extend MockPlatform with Platform::{facts, inspect, read_text}

///|
pub impl Platform for MockPlatform with fn inspect(self, probe) {
  self.observations
  .get(probe_key(probe))
  .unwrap_or(
    finding(
      Unsupported,
      "unsupported",
      "Mock has no observation for this capability",
    ),
  )
}

///|
pub impl Platform for MockPlatform with fn read_text(self, path, limit) {
  match self.files.get(path) {
    None => raise DoctorError("mock file is absent")
    Some(text) => {
      validate_input(text, max_bytes=limit)
      text
    }
  }
}