# SPARQL Queries for CLI Application Generation

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX cli: <http://ggen.dev/ontology/cli#>
PREFIX gen: <http://ggen.dev/ontology/generator#>

# Query 1: Get Command Structure
# Retrieves all commands and subcommands with their hierarchy
CONSTRUCT {
  ?app cli:hasCommand ?cmd .
  ?cmd cli:commandName ?name ;
       cli:commandAbout ?about ;
       cli:hasSubcommand ?subcmd .
  ?subcmd cli:commandName ?subname ;
          cli:commandAbout ?subabout .
}
WHERE {
  ?app a cli:CLIApplication .
  ?app cli:hasCommand ?cmd .
  ?cmd cli:commandName ?name .
  OPTIONAL { ?cmd cli:commandAbout ?about }
  OPTIONAL {
    ?cmd cli:hasSubcommand ?subcmd .
    ?subcmd cli:commandName ?subname .
    OPTIONAL { ?subcmd cli:commandAbout ?subabout }
  }
}

# Query 2: Get Arguments and Options
# Extracts all arguments and options for a command
SELECT ?command ?argName ?argType ?argRequired ?argDefault ?argHelp ?argPosition
       ?optShort ?optLong ?optType ?optRequired ?optDefault ?optHelp ?optMultiple ?enumValues
WHERE {
  ?command a cli:Command .
  OPTIONAL {
    ?command cli:hasArgument ?arg .
    ?arg cli:argumentName ?argName ;
         cli:argumentType ?argTypeObj .
    ?argTypeObj cli:rustType ?argType .
    OPTIONAL { ?arg cli:argumentRequired ?argRequired }
    OPTIONAL { ?arg cli:argumentDefault ?argDefault }
    OPTIONAL { ?arg cli:argumentHelp ?argHelp }
    OPTIONAL { ?arg cli:argumentPosition ?argPosition }
  }
  OPTIONAL {
    ?command cli:hasOption ?opt .
    OPTIONAL { ?opt cli:optionShort ?optShort }
    OPTIONAL { ?opt cli:optionLong ?optLong }
    OPTIONAL {
      ?opt cli:optionType ?optTypeObj .
      ?optTypeObj cli:rustType ?optType
    }
    OPTIONAL { ?opt cli:optionRequired ?optRequired }
    OPTIONAL { ?opt cli:optionDefault ?optDefault }
    OPTIONAL { ?opt cli:optionHelp ?optHelp }
    OPTIONAL { ?opt cli:optionMultiple ?optMultiple }
    OPTIONAL { ?opt cli:optionEnumValues ?enumValues }
  }
}
ORDER BY ?argPosition

# Query 3: Get Validation Rules
# Retrieves validation rules for arguments and options
SELECT ?argument ?validatorType ?pattern ?min ?max ?errorMsg
WHERE {
  ?argument a cli:Argument .
  ?argument cli:hasValidator ?validator .
  ?validator cli:validatorType ?validatorType .
  OPTIONAL { ?validator cli:validatorPattern ?pattern }
  OPTIONAL { ?validator cli:validatorMin ?min }
  OPTIONAL { ?validator cli:validatorMax ?max }
  OPTIONAL { ?validator cli:validatorErrorMessage ?errorMsg }
}

# Query 4: Get Configuration
# Extracts configuration file and environment variable settings
SELECT ?app ?configFormat ?configPath ?envPrefix ?envVarName
WHERE {
  ?app a cli:CLIApplication .
  OPTIONAL {
    ?app cli:hasConfig ?config .
    ?config a cli:ConfigFile .
    ?config cli:configFormat ?configFormat ;
            cli:configPath ?configPath .
  }
  OPTIONAL {
    ?app cli:hasConfig ?env .
    ?env a cli:EnvVar .
    OPTIONAL { ?env cli:envVarPrefix ?envPrefix }
    OPTIONAL { ?env cli:envVarName ?envVarName }
  }
}

# Query 5: Get Help Text and Documentation
# Retrieves help text, examples, and documentation metadata
SELECT ?command ?about ?longAbout ?example ?helpAfter ?template
WHERE {
  ?command a cli:Command .
  OPTIONAL { ?command cli:commandAbout ?about }
  OPTIONAL { ?command cli:commandLongAbout ?longAbout }
  OPTIONAL {
    ?command cli:hasHelp ?help .
    OPTIONAL { ?help cli:helpExample ?example }
    OPTIONAL { ?help cli:helpAfter ?helpAfter }
    OPTIONAL { ?help cli:helpTemplate ?template }
  }
}

# Query 6: Generate Command Struct (Rust)
# Generates Rust struct definition for a command
CONSTRUCT {
  ?command gen:rustStruct ?struct ;
           gen:rustFields ?fields .
}
WHERE {
  ?command a cli:Command ;
           cli:commandName ?name .
  BIND(CONCAT("#[derive(Parser, Debug)]\nstruct ", UCASE(SUBSTR(?name,1,1)), SUBSTR(?name,2), "Args {") AS ?struct)

  {
    SELECT ?command (GROUP_CONCAT(?field; separator="\n    ") AS ?fields)
    WHERE {
      ?command cli:hasArgument ?arg .
      ?arg cli:argumentName ?argName ;
           cli:argumentType ?argTypeObj .
      ?argTypeObj cli:rustType ?argType .
      OPTIONAL { ?arg cli:argumentHelp ?help }

      BIND(CONCAT(
        IF(BOUND(?help), CONCAT("/// ", ?help, "\n    "), ""),
        ?argName, ": ", ?argType, ","
      ) AS ?field)
    }
    GROUP BY ?command
  }
}

# Query 7: Generate Argument Parser (TypeScript)
# Generates TypeScript commander.js code
SELECT ?command ?parserCode
WHERE {
  ?command a cli:Command ;
           cli:commandName ?cmdName ;
           cli:commandAbout ?about .

  {
    SELECT ?command (GROUP_CONCAT(?optionCode; separator="\n  ") AS ?options)
    WHERE {
      ?command cli:hasOption ?opt .
      OPTIONAL { ?opt cli:optionShort ?short }
      ?opt cli:optionLong ?long ;
           cli:optionHelp ?help .

      BIND(CONCAT(
        ".option('",
        IF(BOUND(?short), CONCAT("-", ?short, ", "), ""),
        "--", ?long, "', '", ?help, "')"
      ) AS ?optionCode)
    }
    GROUP BY ?command
  }

  BIND(CONCAT(
    "program\n",
    "  .command('", ?cmdName, "')\n",
    "  .description('", ?about, "')\n",
    COALESCE(?options, ""),
    "\n  .action((options) => {\n",
    "    // Command implementation\n",
    "  });"
  ) AS ?parserCode)
}

# Query 8: Generate Shell Completion
# Generates shell completion script metadata
SELECT ?app ?shell ?completionCode
WHERE {
  ?app a cli:CLIApplication ;
       cli:hasCompletion ?completion .
  ?completion cli:completionShell ?shell .

  # Shell-specific completion generation logic
  BIND(
    IF(?shell = "bash",
       "# Bash completion script\ncomplete -F _mycli mycli",
       IF(?shell = "zsh",
          "# Zsh completion script\ncompdef _mycli mycli",
          "# Fish completion script\ncomplete -c mycli -f"
       )
    ) AS ?completionCode
  )
}

# Query 9: Generate Config File Schema
# Generates configuration file schema (TOML/YAML/JSON)
SELECT ?format ?schema
WHERE {
  ?app a cli:CLIApplication ;
       cli:hasConfig ?config .
  ?config a cli:ConfigFile ;
          cli:configFormat ?format .

  # Get all configurable options
  {
    SELECT ?format (GROUP_CONCAT(?field; separator="\n") AS ?fields)
    WHERE {
      ?cmd cli:hasOption ?opt .
      ?opt cli:optionLong ?name .
      OPTIONAL { ?opt cli:optionDefault ?default }
      OPTIONAL { ?opt cli:optionType ?typeObj }
      OPTIONAL { ?typeObj cli:rustType ?type }

      BIND(
        IF(?format = "toml",
           CONCAT(?name, " = ", COALESCE(?default, '""')),
           IF(?format = "yaml",
              CONCAT(?name, ": ", COALESCE(?default, '""')),
              CONCAT('"', ?name, '": ', COALESCE(?default, 'null'))
           )
        ) AS ?field
      )
    }
    GROUP BY ?format
  }

  BIND(
    IF(?format = "toml",
       CONCAT("[config]\n", ?fields),
       IF(?format = "yaml",
          ?fields,
          CONCAT("{\n  ", ?fields, "\n}")
       )
    ) AS ?schema
  )
}

# Query 10: Generate Interactive Prompts
# Generates interactive prompt code
SELECT ?command ?promptCode
WHERE {
  ?command a cli:Command ;
           cli:hasPrompt ?prompt .
  ?prompt cli:promptType ?type ;
          cli:promptMessage ?message .
  OPTIONAL { ?prompt cli:promptChoices ?choices }

  # TypeScript inquirer code
  BIND(CONCAT(
    "const answer = await inquirer.prompt([\n",
    "  {\n",
    "    type: '", ?type, "',\n",
    "    name: 'value',\n",
    "    message: '", ?message, "'",
    IF(BOUND(?choices), CONCAT(",\n    choices: [", ?choices, "]"), ""),
    "\n  }\n",
    "]);"
  ) AS ?promptCode)
}

# Query 11: Get All Commands for Help Generation
# Retrieves complete command tree for help text
SELECT ?cmdName ?cmdAbout ?subcmdName ?subcmdAbout ?argName ?argHelp ?optLong ?optShort ?optHelp
WHERE {
  ?cmd a cli:Command ;
       cli:commandName ?cmdName .
  OPTIONAL { ?cmd cli:commandAbout ?cmdAbout }

  OPTIONAL {
    ?cmd cli:hasSubcommand ?subcmd .
    ?subcmd cli:commandName ?subcmdName .
    OPTIONAL { ?subcmd cli:commandAbout ?subcmdAbout }
  }

  OPTIONAL {
    ?cmd cli:hasArgument ?arg .
    ?arg cli:argumentName ?argName .
    OPTIONAL { ?arg cli:argumentHelp ?argHelp }
  }

  OPTIONAL {
    ?cmd cli:hasOption ?opt .
    OPTIONAL { ?opt cli:optionLong ?optLong }
    OPTIONAL { ?opt cli:optionShort ?optShort }
    OPTIONAL { ?opt cli:optionHelp ?optHelp }
  }
}
ORDER BY ?cmdName ?subcmdName ?argName

# Query 12: Generate Validation Code
# Generates validation functions for arguments
SELECT ?argName ?validationCode
WHERE {
  ?arg cli:argumentName ?argName ;
       cli:hasValidator ?validator .
  ?validator cli:validatorType ?type .

  OPTIONAL { ?validator cli:validatorPattern ?pattern }
  OPTIONAL { ?validator cli:validatorMin ?min }
  OPTIONAL { ?validator cli:validatorMax ?max }
  OPTIONAL { ?validator cli:validatorErrorMessage ?errorMsg }

  # Generate validation code based on type
  BIND(
    IF(?type = "regex",
       CONCAT("if (!", COALESCE(?pattern, ".*"), ".test(", ?argName, ")) {\n  throw new Error('", COALESCE(?errorMsg, "Invalid input"), "');\n}"),
       IF(?type = "range",
          CONCAT("if (", ?argName, " < ", STR(?min), " || ", ?argName, " > ", STR(?max), ") {\n  throw new Error('", COALESCE(?errorMsg, "Out of range"), "');\n}"),
          "// Custom validation"
       )
    ) AS ?validationCode
  )
}
