// 库入口与 CLI 编排。
// analyze() 把 5 类输入汇总成一个 Report;各 run_* 只做参数解析与输出。

///|
pub fn version() -> String {
  @report.version()
}

///|
pub fn print_usage() -> Unit {
  println(
    "agentsurface \{version()} — capability graph and least-privilege policy for Agent projects",
  )
  println("")
  println("USAGE:")
  println(
    "  agentsurface scan  [--format text|json|sarif|md] [--out ]",
  )
  println(
    "                          [--fail-on critical|high|medium|low|none] [--tools ]...",
  )
  println("  agentsurface graph  [--format mermaid|json] [--out ]")
  println("  agentsurface policy  [--format json|claude] [--out ]")
  println("  agentsurface rules")
  println("  agentsurface version")
  println("")
  println("EXIT CODES:")
  println("  0  no finding at or above --fail-on")
  println("  1  finding at or above --fail-on")
  println("  2  usage error or read failure")
}

///|
pub fn print_rules() -> Unit {
  println("id    severity  name")
  for info in @rules.rule_infos() {
    println(
      "\{pad_right(info.id, 6)}\{pad_right(@model.severity_id(info.severity), 10)}\{info.name}",
    )
  }
}

///|
fn pad_right(text : String, width : Int32) -> String {
  let mut out = text
  while out.length() < width {
    out = out + " "
  }
  out
}

///|
fn add_component(
  components : Array[@model.Component],
  seen : Map[String, Bool],
  component : @model.Component,
) -> Unit {
  match seen.get(component.id) {
    Some(_) => ()
    None => {
      seen.set(component.id, true)
      components.push(component)
    }
  }
}

///|
pub fn analyze(load : @parse.ProjectLoad) -> @model.Report {
  let components : Array[@model.Component] = []
  let facts : Array[@model.CapabilityFact] = []
  let unknowns : Array[String] = []
  let seen : Map[String, Bool] = Map([])
  let settings_allow : Array[String] = []
  let settings_deny : Array[String] = []
  let mut has_settings = false

  for unknown in load.unknowns {
    unknowns.push(unknown)
  }

  for file in load.files {
    match file.kind {
      "mcp_config" =>
        match @parse.parse_mcp_config(file.text) {
          Ok(servers) =>
            for server in servers {
              add_component(components, seen, {
                id: "mcp:" + server.name,
                kind: @model.McpServer,
                name: server.name,
                source: file.path,
              })
              for fact in @infer.infer_server(server, file.path) {
                facts.push(fact)
              }
            }
          Err(message) => unknowns.push(file.path + ": " + message)
        }
      "settings" =>
        match @parse.parse_settings(file.text) {
          Ok(settings) => {
            has_settings = true
            for pattern in settings.allow {
              settings_allow.push(pattern)
            }
            for pattern in settings.deny {
              settings_deny.push(pattern)
            }
            add_component(components, seen, {
              id: "settings",
              kind: @model.Settings,
              name: "settings",
              source: file.path,
            })
            for fact in @infer.infer_settings(settings, file.path) {
              facts.push(fact)
            }
          }
          Err(message) => unknowns.push(file.path + ": " + message)
        }
      "skill" => {
        let skill = @parse.parse_skill_md(file.text)
        add_component(components, seen, {
          id: "skill:" + skill.name,
          kind: @model.Skill,
          name: skill.name,
          source: file.path,
        })
        for fact in @infer.infer_skill(skill, file.path) {
          facts.push(fact)
        }
      }
      "tools_snapshot" =>
        match @parse.parse_tools_snapshot(file.text) {
          Ok(tools) =>
            for tool in tools {
              add_component(components, seen, {
                id: "tool:" + tool.name,
                kind: @model.Tool,
                name: tool.name,
                source: file.path,
              })
              for fact in @infer.infer_tool(tool, file.path) {
                facts.push(fact)
              }
            }
          Err(message) => unknowns.push(file.path + ": " + message)
        }
      "script" => {
        let script = @parse.parse_script(file.path, file.text)
        add_component(components, seen, {
          id: "script:" + file.path,
          kind: @model.Script,
          name: file.path,
          source: file.path,
        })
        for fact in @infer.infer_script(script, file.path) {
          facts.push(fact)
        }
      }
      _ => unknowns.push(file.path + ": 未识别的输入类型 " + file.kind)
    }
  }

  let findings = @rules.evaluate({
    components,
    facts,
    settings_allow,
    settings_deny,
    has_settings,
  })
  let policy = @policy.build(facts, findings)
  return {
    project_root: load.root,
    components,
    facts,
    findings,
    policy,
    unknowns,
  }
}

///|
pub fn analyze_project(root : String) -> @model.Report {
  analyze(@parse.load_project(root))
}

///|
fn fail_rank(name : String) -> Int32 {
  match name {
    "none" => -1
    "low" => 1
    "medium" => 2
    "high" => 3
    "critical" => 4
    _ => 3
  }
}

///|
fn should_fail(findings : Array[@model.Finding], threshold : Int32) -> Bool {
  if threshold < 0 {
    return false
  }
  for finding in findings {
    if @model.severity_rank(finding.severity) >= threshold {
      return true
    }
  }
  false
}

///|
fn emit(output : String, out_path : String) -> Unit {
  if out_path == "" {
    println(output)
  } else {
    @fs.write_string_to_file(out_path, output) catch {
      _ => {
        println("agentsurface: cannot write " + out_path)
        exit_error()
      }
    }
  }
}

///|
fn read_extra_tools(
  paths : Array[String],
  files : Array[@parse.ProjectFile],
) -> Bool {
  for path in paths {
    let text = @fs.read_file_to_string(path) catch {
      _ => {
        println("agentsurface: cannot read " + path)
        return false
      }
    }
    files.push({ path, kind: "tools_snapshot", text, })
  }
  true
}

///|
fn take_value(args : ArrayView[String], index : Int32) -> String? {
  if index + 1 < args.length() {
    Some(args[index + 1])
  } else {
    None
  }
}

///|
pub fn run_scan(args : ArrayView[String]) -> Unit {
  let mut root = "."
  let mut format = "text"
  let mut out_path = ""
  let mut fail_on = "high"
  let tools : Array[String] = []
  let mut i = 0
  while i < args.length() {
    let arg = args[i]
    if arg == "--format" {
      match take_value(args, i) {
        Some(value) => {
          format = value
          i += 2
        }
        None => {
          usage_error("--format requires a value")
          return
        }
      }
    } else if arg == "--out" {
      match take_value(args, i) {
        Some(value) => {
          out_path = value
          i += 2
        }
        None => {
          usage_error("--out requires a value")
          return
        }
      }
    } else if arg == "--fail-on" {
      match take_value(args, i) {
        Some(value) => {
          fail_on = value
          i += 2
        }
        None => {
          usage_error("--fail-on requires a value")
          return
        }
      }
    } else if arg == "--tools" {
      match take_value(args, i) {
        Some(value) => {
          tools.push(value)
          i += 2
        }
        None => {
          usage_error("--tools requires a value")
          return
        }
      }
    } else if arg.has_prefix("--") {
      usage_error("unknown option: " + arg)
      return
    } else {
      root = arg
      i += 1
    }
  }
  if !@fs.path_exists(root) {
    usage_error("path not found: " + root)
    return
  }
  if !(@fs.is_dir(root) catch { _ => false }) {
    usage_error("not a directory: " + root)
    return
  }
  let load = @parse.load_project(root)
  if !read_extra_tools(tools, load.files) {
    exit_error()
    return
  }
  let report = analyze(load)
  let output = match format {
    "text" => @report.render_text(report)
    "json" => @report.render_json(report)
    "sarif" => @report.render_sarif(report)
    "md" | "markdown" => @report.render_markdown(report)
    _ => {
      usage_error("unknown format: " + format)
      return
    }
  }
  emit(output, out_path)
  if should_fail(report.findings, fail_rank(fail_on)) {
    exit_blocked()
  } else {
    exit_ok()
  }
}

///|
pub fn run_graph(args : ArrayView[String]) -> Unit {
  let mut root = "."
  let mut format = "mermaid"
  let mut out_path = ""
  let mut i = 0
  while i < args.length() {
    let arg = args[i]
    if arg == "--format" {
      match take_value(args, i) {
        Some(value) => {
          format = value
          i += 2
        }
        None => {
          usage_error("--format requires a value")
          return
        }
      }
    } else if arg == "--out" {
      match take_value(args, i) {
        Some(value) => {
          out_path = value
          i += 2
        }
        None => {
          usage_error("--out requires a value")
          return
        }
      }
    } else if arg.has_prefix("--") {
      usage_error("unknown option: " + arg)
      return
    } else {
      root = arg
      i += 1
    }
  }
  if !@fs.path_exists(root) {
    usage_error("path not found: " + root)
    return
  }
  let report = analyze_project(root)
  let graph = @graph.build(report)
  let output = match format {
    "mermaid" | "md" => @graph.render_mermaid(graph)
    "json" => @graph.render_json(graph)
    _ => {
      usage_error("unknown format: " + format)
      return
    }
  }
  emit(output, out_path)
  exit_ok()
}

///|
pub fn run_policy(args : ArrayView[String]) -> Unit {
  let mut root = "."
  let mut format = "json"
  let mut out_path = ""
  let mut i = 0
  while i < args.length() {
    let arg = args[i]
    if arg == "--format" {
      match take_value(args, i) {
        Some(value) => {
          format = value
          i += 2
        }
        None => {
          usage_error("--format requires a value")
          return
        }
      }
    } else if arg == "--out" {
      match take_value(args, i) {
        Some(value) => {
          out_path = value
          i += 2
        }
        None => {
          usage_error("--out requires a value")
          return
        }
      }
    } else if arg.has_prefix("--") {
      usage_error("unknown option: " + arg)
      return
    } else {
      root = arg
      i += 1
    }
  }
  if !@fs.path_exists(root) {
    usage_error("path not found: " + root)
    return
  }
  let report = analyze_project(root)
  let output = match format {
    "json" => @policy.render_json(report.policy)
    "claude" => @policy.render_claude(report.policy)
    _ => {
      usage_error("unknown format: " + format)
      return
    }
  }
  emit(output, out_path)
  exit_ok()
}

///|
fn usage_error(message : String) -> Unit {
  println("agentsurface: " + message)
  print_usage()
  exit_error()
}