///|
/// Built-in framework presets.
///
/// A preset is a named, ready-to-use rule set for a popular frontend
/// framework. Presets are defined as MoonBit data (not JSON strings) so the
/// patterns stay readable and cannot drift from what the engine compiles.
/// The same rule sets are also shipped as JSON files under `presets/` for
/// users who prefer to copy and customize them.
///
/// Presets are pure rule collections: they carry no global scope, so merging
/// several presets is a simple concatenation with de-duplication by rule id
/// (the first occurrence wins). Rule-level `include` / `exclude` scopes are
/// preserved as declared.
///
/// Most rules are line-oriented: they match one source line at a time, after
/// comments have been blanked out. The `imports` preset goes further and
/// uses the project-level structural rules, which parse every scanned file
/// and reason across them (unused imports, unresolved specifiers, import
/// cycles, dead exports).

///|
/// A built-in preset: a name, a one-line description, and its rules.
pub struct Preset {
  /// Stable preset name, e.g. `react`.
  name : String
  /// One-line description shown by `--list-presets`.
  description : String
  /// The preset's rules, in declaration order.
  rules : Array[Rule]
  /// The preset's file-level rules.
  file_rules : Array[FileRule]
  /// The preset's project-level structural rules.
  structural_rules : Array[StructuralRule]
}

///|
/// Shorthand constructor for a structural rule with no scope.
fn structural(
  id : String,
  severity : Severity,
  message : String,
  extensions : Array[String],
  check : StructuralCheck,
) -> StructuralRule {
  StructuralRule::{
    id,
    severity,
    message,
    extensions,
    check,
    scope: Scope::empty(),
  }
}

///|
/// Shorthand constructor for a rule with no `unless` guard and no scope.
fn rule(
  id : String,
  severity : Severity,
  message : String,
  extensions : Array[String],
  match_ : MatchKind,
) -> Rule {
  Rule::{
    id,
    severity,
    message,
    extensions,
    match_,
    unless: None,
    scope: Scope::empty(),
    match_comments: false,
    match_literals: false,
  }
}

///|
/// Shorthand constructor for a rule with an `unless` guard.
fn guarded_rule(
  id : String,
  severity : Severity,
  message : String,
  extensions : Array[String],
  match_ : MatchKind,
  unless : MatchKind,
) -> Rule {
  Rule::{
    id,
    severity,
    message,
    extensions,
    match_,
    unless: Some(unless),
    scope: Scope::empty(),
    match_comments: false,
    match_literals: false,
  }
}

///|
/// Shorthand constructor for a rule that targets comments themselves, so it
/// matches the raw (comment-inclusive) view instead of the stripped one.
fn comment_rule(
  id : String,
  severity : Severity,
  message : String,
  extensions : Array[String],
  match_ : MatchKind,
) -> Rule {
  Rule::{
    id,
    severity,
    message,
    extensions,
    match_,
    unless: None,
    scope: Scope::empty(),
    match_comments: true,
    match_literals: false,
  }
}

///|
/// Shorthand constructor for a rule whose target exists only as literal text
/// — an attribute value such as `target="_blank"`, or a module specifier such
/// as `from 'react'`. Such a rule matches the literal view (literal contents
/// intact) instead of the default code view, where those values are blanked.
fn literal_rule(
  id : String,
  severity : Severity,
  message : String,
  extensions : Array[String],
  match_ : MatchKind,
) -> Rule {
  Rule::{
    id,
    severity,
    message,
    extensions,
    match_,
    unless: None,
    scope: Scope::empty(),
    match_comments: false,
    match_literals: true,
  }
}

///|
/// Shorthand constructor for a literal-view rule with an `unless` guard. The
/// guard sees the same literal view as the matcher, so an exemption written
/// against literal text (for example `display=swap` inside an href) keeps
/// working.
fn literal_guarded_rule(
  id : String,
  severity : Severity,
  message : String,
  extensions : Array[String],
  match_ : MatchKind,
  unless : MatchKind,
) -> Rule {
  Rule::{
    id,
    severity,
    message,
    extensions,
    match_,
    unless: Some(unless),
    scope: Scope::empty(),
    match_comments: false,
    match_literals: true,
  }
}

// ---------------------------------------------------------------------------
// common — framework-agnostic JavaScript/TypeScript hygiene
// ---------------------------------------------------------------------------

///|
fn common_rules() -> Array[Rule] {
  [
    rule(
      "common/no-console-log",
      Severity::warning(),
      "Avoid console.log in committed code",
      [
        ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".vue", ".svelte", ".astro",
      ],
      Contains("console.log"),
    ),
    rule(
      "common/no-debugger",
      Severity::error(),
      "No debugger statements",
      [
        ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".vue", ".svelte", ".astro",
      ],
      Regex("^[[:space:]]*debugger[[:space:]]*;?[[:space:]]*$"),
    ),
    rule(
      "common/no-alert",
      Severity::warning(),
      "Avoid alert(), confirm() and prompt() in production code",
      [
        ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".vue", ".svelte", ".astro",
      ],
      Regex("\\b(alert|confirm|prompt)\\("),
    ),
    rule(
      "common/no-eval",
      Severity::error(),
      "Avoid eval() and its implicit forms",
      [
        ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".vue", ".svelte", ".astro",
      ],
      Regex("\\beval\\("),
    ),
    rule(
      "common/no-var",
      Severity::warning(),
      "Use let or const instead of var",
      [
        ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".vue", ".svelte", ".astro",
      ],
      Regex("\\bvar[[:space:]]"),
    ),
    comment_rule(
      "common/no-todo-comment",
      Severity::warning(),
      "TODO/FIXME comment left in code",
      [
        ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".vue", ".svelte", ".astro",
      ],
      Any([Word("TODO"), Word("FIXME")]),
    ),
  ]
}

// ---------------------------------------------------------------------------
// react — React and JSX conventions
// ---------------------------------------------------------------------------

///|
fn react_rules() -> Array[Rule] {
  let jsx = [".jsx", ".tsx"]
  [
    rule(
      "react/no-danger",
      Severity::error(),
      "Avoid dangerouslySetInnerHTML (XSS risk)",
      jsx,
      Contains("dangerouslySetInnerHTML"),
    ),
    rule(
      "react/no-find-dom-node",
      Severity::error(),
      "Avoid findDOMNode (breaks encapsulation)",
      jsx,
      Contains("findDOMNode"),
    ),
    rule(
      "react/no-string-refs",
      Severity::error(),
      "Avoid string refs; use callback refs or createRef",
      jsx,
      Regex("(^|[[:space:]])ref=\""),
    ),
    rule(
      "react/no-children-prop",
      Severity::error(),
      "Avoid passing children as a prop; use nesting instead",
      jsx,
      Contains("children="),
    ),
    rule(
      "react/no-array-index-key",
      Severity::warning(),
      "Avoid using the array index as a key",
      jsx,
      Regex("key=\\{(i|idx|[[:alpha:]_]*(?i:index)[[:alpha:]_]*)\\}"),
    ),
    rule(
      "react/no-deprecated",
      Severity::error(),
      "Avoid deprecated lifecycle methods (componentWillMount/ReceiveProps/Update)",
      jsx,
      Regex("componentWillMount|componentWillReceiveProps|componentWillUpdate"),
    ),
    rule(
      "react/no-is-mounted",
      Severity::error(),
      "Avoid isMounted (anti-pattern)",
      jsx,
      Regex("\\.isMounted\\("),
    ),
    rule(
      "react/prefer-es6-class",
      Severity::error(),
      "Avoid React.createClass; use ES6 classes or function components",
      jsx,
      Regex("React\\.createClass|createReactClass"),
    ),
    rule(
      "react/self-closing-comp",
      Severity::warning(),
      "Use self-closing tags for empty elements",
      jsx,
      Regex(">"),
    ),
    literal_guarded_rule(
      "react/jsx-no-target-blank",
      Severity::warning(),
      "target=\"_blank\" without rel=\"noopener\" is a security risk",
      jsx,
      Regex("target=\"_blank\""),
      Regex("noopener"),
    ),
    literal_rule(
      "react/jsx-no-script-url",
      Severity::error(),
      "Avoid javascript: URLs in href",
      jsx,
      Regex("href=\"javascript:"),
    ),
    rule(
      "react/style-prop-object",
      Severity::error(),
      "The style prop must be an object, not a string",
      jsx,
      Regex("(^|[[:space:]])style=\""),
    ),
    rule(
      "react/jsx-props-no-spreading",
      Severity::warning(),
      "Avoid spreading props ({...props}); pass them explicitly",
      jsx,
      Regex("\\{\\.\\.\\."),
    ),
    rule(
      "react/jsx-curly-brace-presence",
      Severity::warning(),
      "Remove unnecessary curly braces around string literals",
      jsx,
      Regex("=\\{\"[^\"]*\"\\}"),
    ),
    rule(
      "react/jsx-boolean-value",
      Severity::warning(),
      "Use shorthand for boolean props (disabled instead of disabled={true})",
      jsx,
      Regex("=\\{true\\}"),
    ),
    rule(
      "react/no-unknown-property",
      Severity::error(),
      "Use className instead of class in JSX",
      jsx,
      Regex("(^|[[:space:]])class="),
    ),
    guarded_rule(
      "react/button-has-type",
      Severity::warning(),
      "Buttons must have an explicit type attribute",
      jsx,
      Regex("... instead of ",
      jsx,
      Regex(" Array[Rule] {
  let vue_exts = [".vue", ".js", ".ts"]
  [
    rule(
      "vue/no-v-html",
      Severity::warning(),
      "Avoid v-html (XSS risk); use text interpolation or a sanitizer",
      vue_exts,
      Contains("v-html"),
    ),
    guarded_rule(
      "vue/require-v-for-key",
      Severity::error(),
      "v-for requires a :key binding",
      vue_exts,
      Regex("v-for"),
      Regex(":key|v-bind:key"),
    ),
    rule(
      "vue/no-use-v-if-with-v-for",
      Severity::error(),
      "Avoid using v-if and v-for on the same element",
      vue_exts,
      Regex("v-for[^>]*v-if|v-if[^>]*v-for"),
    ),
    guarded_rule(
      "vue/require-component-is",
      Severity::error(),
      " requires an :is binding",
      vue_exts,
      Regex(" blocks should be scoped",
      [".vue"],
      Regex(" Array[Rule] {
  let ts = [".ts"]
  [
    rule(
      "angular/no-input-rename",
      Severity::error(),
      "Avoid renaming @Input() with an alias",
      ts,
      Regex("@Input\\(['\"]"),
    ),
    rule(
      "angular/no-output-rename",
      Severity::error(),
      "Avoid renaming @Output() with an alias",
      ts,
      Regex("@Output\\(['\"]"),
    ),
    rule(
      "angular/no-output-native",
      Severity::error(),
      "Avoid @Output() names that collide with native DOM events",
      ts,
      Regex(
        "@Output\\(\\)[[:space:]]*(click|change|focus|blur|submit|input|keydown|keyup|keypress|mousedown|mouseup|mouseenter|mouseleave|dblclick|contextmenu|wheel|scroll|select|load|error|abort|resize)",
      ),
    ),
    rule(
      "angular/no-output-on-prefix",
      Severity::warning(),
      "Avoid the on prefix in @Output() names",
      ts,
      Regex("@Output\\(\\)[[:space:]]*on"),
    ),
    rule(
      "angular/no-input-prefix",
      Severity::warning(),
      "Avoid the on prefix in @Input() names",
      ts,
      Regex("@Input\\(\\)[[:space:]]*on"),
    ),
    rule(
      "angular/no-forward-ref",
      Severity::warning(),
      "Avoid forwardRef; restructure dependencies instead",
      ts,
      Contains("forwardRef"),
    ),
    rule(
      "angular/no-host-metadata-property",
      Severity::warning(),
      "Use @HostListener instead of the host metadata property",
      ts,
      Regex("^[[:space:]]*host:"),
    ),
    rule(
      "angular/no-attribute-decorator",
      Severity::error(),
      "Avoid @Attribute(); use @Inject() or a service instead",
      ts,
      Regex("@Attribute\\("),
    ),
    literal_guarded_rule(
      "angular/relative-url-prefix",
      Severity::error(),
      "Relative templateUrl/styleUrls must start with ./",
      ts,
      Regex("templateUrl:|styleUrls?:"),
      Regex("(templateUrl|styleUrls?):[[:space:]]*\\[?[[:space:]]*['\"]\\./"),
    ),
  ]
}

// ---------------------------------------------------------------------------
// svelte — Svelte component conventions
// ---------------------------------------------------------------------------

///|
fn svelte_rules() -> Array[Rule] {
  let svelte = [".svelte"]
  [
    rule(
      "svelte/no-at-html-tags",
      Severity::warning(),
      "Avoid {@html} (XSS risk); use text interpolation or a sanitizer",
      svelte,
      Regex("\\{@html"),
    ),
    guarded_rule(
      "svelte/no-target-blank",
      Severity::warning(),
      "target=\"_blank\" without rel=\"noopener\" is a security risk",
      svelte,
      Regex("target=\"_blank\""),
      Regex("noopener"),
    ),
    guarded_rule(
      "svelte/require-each-key",
      Severity::error(),
      "{#each} blocks require a key expression",
      svelte,
      Regex("\\{#each"),
      Regex("\\([^)]+\\)\\}"),
    ),
    rule(
      "svelte/no-reactive-literals",
      Severity::warning(),
      "Avoid reactive statements that assign a literal",
      svelte,
      Regex(
        "\\$:[[:space:]]*[[:alpha:]_$][[:alnum:]_$]*[[:space:]]*=[[:space:]]*[\"'[:digit:]]",
      ),
    ),
    rule(
      "svelte/prefer-style-directive",
      Severity::warning(),
      "Use the style: directive instead of inline style with interpolation",
      svelte,
      Regex("style=\"[^\"]*\\{"),
    ),
    guarded_rule(
      "svelte/a11y-mouse-events-have-key-events",
      Severity::warning(),
      "on:mouseover/on:mouseout must be paired with keyboard events",
      svelte,
      Regex("on:mouseover|on:mouseout"),
      Regex("on:keydown|on:keyup|on:focus|on:blur"),
    ),
    guarded_rule(
      "svelte/a11y-missing-attribute",
      Severity::error(),
      " requires an alt attribute",
      svelte,
      Regex(" Array[Rule] {
  let next_exts = [".jsx", ".tsx", ".js", ".ts"]
  [
    literal_rule(
      "next/no-html-link-for-pages",
      Severity::warning(),
      "Use  instead of  for internal pages",
      next_exts,
      Regex("]*href=\"/"),
    ),
    rule(
      "next/no-img-element",
      Severity::warning(),
      "Use next/image instead of ",
      next_exts,
      Regex("",
      next_exts,
      Regex("",
      next_exts,
      Regex("]*rel=\"stylesheet\""),
    ),
    guarded_rule(
      "next/no-sync-scripts",
      Severity::warning(),
      "Synchronous