// The command table: parsing, help text, and the dispatch that maps one command
// to an outcome. `src/fus` is only the entrypoint that calls `dispatch`.

///|
/// What `clean` should delete.
///
/// `OutputAndCache` is the default; the narrower scopes exist for CI jobs that
/// want to keep the incremental cache between builds.
#derive(Eq)
pub(all) enum CleanScope {
  OutputOnly
  CacheOnly
  OutputAndCache
}

///|
/// A parsed top-level CLI command.
///
/// `dispatch` turns one of these into an `Outcome`, which is all `main` needs.
pub enum Command {
  Help(String?)
  Version
  Init(String)
  Clean(@build.BuildOptions, CleanScope)
  Serve(@build.BuildOptions, Int32)
  Run(@build.BuildOptions, Int32)
  Check(@build.BuildOptions)
  Build(@build.BuildOptions)
  Unknown(String)
}

///|
/// What the executable should do after the shared dispatch has run.
///
/// `serve` and `run` need the HTTP server, which lives in its own package, so
/// `dispatch` hands them back to the caller instead of running them.
pub(all) enum Outcome {
  /// The command finished successfully; exit with status 0.
  Done
  /// The command reported an error; exit with status 1.
  Fail
  /// The command needs the dev server: command name, options and port.
  Serve(String, @build.BuildOptions, Int32)
}

///|
/// Print the command list, or the usage of one command when `topic` is set.
pub fn help(topic~ : String? = None) -> Unit {
  match topic {
    Some(name) => println(command_help(name))
    None =>
      println(
        "fus - a fast static site generator for MoonBit\n\nUsage:\n  fus  [options]\n\nCommands:\n  build            Build the site into the output directory (default)\n  run              Build, then serve and watch the site\n  serve            Serve the site, rebuilding on change\n  check            Validate config, layouts, includes and permalinks\n  init [DIR]       Create a new site skeleton\n  clean            Remove the output and cache directories\n  help [COMMAND]   Show this help, or the usage of one command\n  version          Print the version\n\nOptions:\n  --root DIR       Site root (default: current directory)\n  --dest DIR       Output directory override\n  --config FILE    Configuration file override\n  --port N         HTTP port for run/serve (default: 8000)\n  --force          Ignore the incremental cache\n  --drafts         Include pages marked as drafts\n  -q, --quiet      Suppress the build summary\n  -v, --version    Print version\n  -h, --help       Show this help\n\nFormats:\n  config           fus.config.yaml | .yml | .json | .toml | .ini\n  pages            .md .markdown .html .htm .jinja .j2 .liquid\n  templates        .jinja / .j2 use Jinja, .liquid uses Liquid\n  data             _data/*.yaml .yml .json .toml .ini .md\n\nRun `fus help ` for the options of one command.\n",
      )
  }
}

// Usage text for one command, used by `help `.

///|
fn command_help(name : String) -> String {
  match name {
    "build" =>
      "fus build [--root DIR] [--dest DIR] [--config FILE] [--force] [--drafts] [-q]\n\nScans content, renders pages, copies assets and writes only changed files.\nThis is the default command when none is given."
    "run" =>
      "fus run [--root DIR] [--port N] [--force] [--drafts] [-q]\n\nBuilds once, then serves the output and rebuilds whenever a file under the\nsite root changes."
    "serve" =>
      "fus serve [--root DIR] [--port N] [--force] [--drafts]\n\nSame pipeline as `run`; kept for scripts that name the server explicitly."
    "check" =>
      "fus check [--root DIR] [--config FILE] [--drafts]\n\nValidates the site without writing output: configuration syntax, missing\ncontent/layout directories, unclosed front matter, missing layouts, layout\ncycles, missing includes, duplicate permalinks, unknown plugins and drafts.\nExits with status 1 when an error is found."
    "init" =>
      "fus init [DIR]\n\nCreates a complete example site at DIR (default `.'): configuration,\nJinja layouts, an include, a data file, Markdown pages with pagination and a\nstylesheet. Existing files are only rewritten when their content differs."
    "clean" =>
      "fus clean [--root DIR] [--dest DIR] [--config FILE] [--cache] [--output]\n\nRemoves the generated output and the incremental cache. `--output` keeps the\ncache, `--cache` keeps the output. Content sources are never touched; a dest\nthat resolves to the site root is refused."
    "help" =>
      "fus help [COMMAND]\n\nWithout an argument, prints the command list."
    "version" =>
      "fus version\n\nPrints the version line. `-v` and `--version` do the same."
    other => "Unknown command: \{other}\n\nRun `fus help` for the command list."
  }
}

///|
/// Print the tool version line.
pub fn print_version() -> Unit {
  println("fus \{@core.version}")
}

// Read the value following an option, or an empty string when absent.

///|
fn take_value(args : Array[String], i : Int32) -> String {
  if i + 1 < args.length() {
    args[i + 1]
  } else {
    ""
  }
}

///|
/// Parse global options after the command name.
///
/// Returns the resulting build options and the requested HTTP port. Unknown
/// tokens are ignored so that subcommands can grow without breaking callers.
pub fn parse_options(
  args : Array[String],
  options : @build.BuildOptions,
) -> (@build.BuildOptions, Int32) {
  let mut root = options.root
  let mut config = options.config
  let mut dest = options.dest
  let mut force = options.force
  let mut drafts = options.drafts
  let mut quiet = options.quiet
  let mut port = 8000
  let mut i = 0
  while i < args.length() {
    let arg = args[i]
    match arg {
      "--root" => {
        root = take_value(args, i)
        i += 1
      }
      "--dest" => {
        dest = Some(take_value(args, i))
        i += 1
      }
      "--config" => {
        config = Some(take_value(args, i))
        i += 1
      }
      "--port" => {
        let raw = take_value(args, i)
        match @core.parse_int(raw) {
          Some(n) if n > 0 && n < 65536 => port = n
          _ => println("warning: ignoring invalid port \"{raw}\"")
        }
        i += 1
      }
      "--force" => force = true
      "--drafts" => drafts = true
      "-q" | "--quiet" => quiet = true
      _ => ()
    }
    i += 1
  }
  (@build.make_options(root, config, dest, force, drafts, quiet), port)
}

// Read the `clean` scope flags; `--output` and `--cache` may be combined.

///|
fn parse_clean_scope(args : Array[String]) -> CleanScope {
  let mut output = false
  let mut cache = false
  for arg in args {
    if arg == "--output" {
      output = true
    } else if arg == "--cache" {
      cache = true
    } else if arg == "--all" {
      output = true
      cache = true
    }
  }
  if output && !cache {
    OutputOnly
  } else if cache && !output {
    CacheOnly
  } else {
    OutputAndCache
  }
}

///|
/// Parse `argv` into a command for the caller to execute.
///
/// `argv[0]` is the program name, as in `@env.args()`; the subcommand is
/// `argv[1]`. An argv with no subcommand builds the current directory, so
/// `parse_command(["fus"])` is the same as `parse_command(["fus", "build"])`.
/// Passing subcommand arguments without the program name (`["check"]`) builds
/// instead, because `check` lands in the program-name slot.
pub fn parse_command(args : Array[String]) -> Command {
  let command = if args.length() > 1 { args[1] } else { "build" }
  match command {
    "-h" | "--help" | "help" =>
      Help(if args.length() > 2 { Some(args[2]) } else { None })
    "-v" | "--version" | "version" => Version
    "init" | "new" => {
      // `fus init --root my-site` means the same as `fus init my-site`; without
      // this, `--root` was taken as the directory name and created `./--root`.
      let (opts, _) = parse_options(args, @build.default_options())
      let dir = if args.length() > 2 && !args[2].has_prefix("-") {
        args[2]
      } else {
        opts.root
      }
      Init(dir)
    }
    "clean" => {
      let (opts, _) = parse_options(args, @build.default_options())
      Clean(opts, parse_clean_scope(args))
    }
    "serve" => {
      let (opts, port) = parse_options(args, @build.default_options())
      Serve(opts, port)
    }
    "run" => {
      let (opts, port) = parse_options(args, @build.default_options())
      Run(opts, port)
    }
    "check" => {
      let (opts, _) = parse_options(args, @build.default_options())
      Check(opts)
    }
    "build" => {
      let (opts, _) = parse_options(args, @build.default_options())
      Build(opts)
    }
    other => Unknown(other)
  }
}

///|
/// Run one command from the process arguments.
///
/// This is the single place that knows how a command maps to an action, so the
/// `main` only has to start the server when this returns `Serve`.
pub async fn dispatch(args : Array[String]) -> Outcome {
  match parse_command(args) {
    Help(topic) => {
      help(topic~)
      Done
    }
    Version => {
      print_version()
      Done
    }
    Init(root) => {
      init_site(root)
      Done
    }
    Clean(opts, scope) => if clean_site(opts, scope) { Done } else { Fail }
    Build(opts) => {
      build_command(opts)
      Done
    }
    Check(opts) => if check_command(opts) { Done } else { Fail }
    Serve(opts, port) => Serve("serve", opts, port)
    Run(opts, port) => Serve("run", opts, port)
    Unknown(other) => {
      println("Unknown command: \{other}")
      help()
      Fail
    }
  }
}

///|
/// Scaffold a complete example site at `root`.
pub async fn init_site(root : String) -> Unit {
  @core.ensure_dir(root) |> ignore
  @core.ensure_dir("\{root}/_layouts") |> ignore
  @core.ensure_dir("\{root}/_includes") |> ignore
  @core.ensure_dir("\{root}/_data") |> ignore
  @core.ensure_dir("\{root}/content") |> ignore
  @core.ensure_dir("\{root}/static") |> ignore
  @core.write_if_changed(
    "\{root}/fus.config.yaml",
    "site:\n  title: My Fus Site\n  description: Built with MoonBit\n  url: http://localhost:8000\n\n# Layouts, includes, data, static and the output directory use their defaults.\nsrcDir: content\n\n# Built-in output generators; Fus has no third-party plugin API.\nplugins: [sitemap, rss, robots]\n",
  )
  |> ignore
  @core.write_if_changed(
    "\{root}/_layouts/base.jinja",
    "\n\n\n  \n  {{ page.title | default(site.title) }}\n  \n\n\n  
{{ site.title }}
\n
{{ body }}
\n
Powered by Fus
\n\n\n", ) |> ignore @core.write_if_changed( "\{root}/_layouts/post.jinja", "---\nlayout: base\n---\n
\n

{{ page.title }}

\n \n {{ body }}\n
\n", ) |> ignore @core.write_if_changed( "\{root}/_includes/hello.jinja", "Hello from an include: {{ site.title }}\n", ) |> ignore @core.write_if_changed("\{root}/_data/site.yaml", "author: Fus User\n") |> ignore @core.write_if_changed( "\{root}/content/index.md", "---\ntitle: Home\nlayout: base\n---\n# Welcome to Fus\n\nThis page was generated by **Fus**, the MoonBit static site generator.\n\n{% include \"hello\" %}\n\n- Fast native builds\n- Incremental caching\n- Markdown, Jinja templates, data and plugins\n", ) |> ignore @core.write_if_changed( "\{root}/content/blog/hello-fus.md", "---\ntitle: Hello Fus\nlayout: post\ndate: 2026-12-01\ntags: [moonbit, static-site]\ndescription: A first post built with Fus.\n---\nFus renders Markdown into HTML and applies your layouts automatically.\n\n```moonbit\nfn main {\n println(\"hello\")\n}\n```\n", ) |> ignore @core.write_if_changed( "\{root}/content/blog/second-post.md", "---\ntitle: Second Post\nlayout: post\ndate: 2026-11-20\ntags: [moonbit]\ndescription: Another post.\n---\nCollections, tags and pagination are derived from front matter.\n", ) |> ignore @core.write_if_changed( "\{root}/content/blog/third-post.md", "---\ntitle: Third Post\nlayout: post\ndate: 2026-11-10\ntags: [static-site]\n---\nCollections and pagination are derived from front matter.\n", ) |> ignore @core.write_if_changed( "\{root}/content/blog/index.md", "---\ntitle: Archive\nlayout: base\npaginate: 2\ncollectionSrc: blog\n---\n# Archive\n\n{% for post in pagination.pages %}\n- [{{ post.title }}]({{ post.url }}) — {{ post.date }}\n{% endfor %}\n", ) |> ignore @core.write_if_changed( "\{root}/static/style.css", "body { max-width: 720px; margin: 2rem auto; font-family: system-ui, sans-serif; }\n", ) |> ignore println("Created a sample site at \{root}") } ///| /// Remove generated output, the incremental cache, or both. /// /// Paths come from the loaded configuration, so `--root` alone is enough even /// when the site writes to a custom `dest`. Content files are never touched. /// Returns false, without deleting anything, when the output resolves to the /// site root: `dest: .` or a `..` segment would otherwise erase the sources. pub async fn clean_site( options : @build.BuildOptions, scope : CleanScope, ) -> Bool { let cfg = @config.load_config( options.root, options.config, options.dest, options.force, ) let output = cfg.output_path() let cache = cfg.cache_path() if unsafe_output(options.root, output) { println( "Refusing to clean \{output}: it resolves to the site root or above. Fix `dest` first.", ) return false } let removed : Array[String] = [] if scope != CacheOnly && @fs.exists(output) { @fs.remove(output, recursive=true) |> ignore removed.push(output) } if scope != OutputOnly && @fs.exists(cache) { @fs.remove(cache, recursive=true) |> ignore removed.push(cache) } if removed.length() == 0 { println("Nothing to clean") } else { println("Removed \{removed.join(", ")}") } true } // Whether deleting `output` would take the site root (or a parent) with it. // // `dest: .` and `dest: ./` both resolve, through `join_path`, to `/.`, // which is the root once the `.` segments are dropped. ///| fn unsafe_output(root : String, output : String) -> Bool { match canonical_path(output) { None => true Some(out) => if out == "" { true } else { out == canonical_path(root).unwrap_or("") } } } // Collapse `.` segments and reject any `..`, or None when the path climbs out. ///| fn canonical_path(path : String) -> String? { let parts : Array[String] = [] for part in @core.normalize_slashes(path).split("/") { if part == "" || part == "." { continue } if part == ".." { return None } parts.push(part.to_owned()) } Some(parts.join("/")) } ///| /// Build a site and print the summary unless quiet mode is requested. pub async fn build_command(options : @build.BuildOptions) -> Unit { let result = @build.build_site(options) if !options.quiet { println( "Built \{result.pages} pages, \{result.generated} paginated, \{result.assets} assets in \{result.elapsed_ms} ms (\{result.writes} writes, \{result.skipped} cached)", ) } for warning in result.warnings { println("warning: \{warning}") } } ///| /// Validate a site and print every finding. /// /// Returns true when no errors were found. Warnings do not fail the check, so /// this suits a CI gate while leaving room for non-fatal notes. pub async fn check_command(options : @build.BuildOptions) -> Bool { let report = @check.check_site(options) for issue in report.issues { println("\{issue.level_name()}: \{issue.message}") } let summary = "Checked \{report.pages} pages, \{report.assets} assets: \{report.errors} errors, \{report.warnings} warnings" println(summary) report.is_ok() }