# Common flag parsing and validation
# Centralized flag handling to reduce code duplication

use ../lib_provisioning/config/accessor.nu *
use ../lib_provisioning/workspace/notation.nu *

# Parse common flags into a normalized record
# This eliminates repetitive flag checking across command handlers
export def parse_common_flags [flags: record] {
  {
    # Version and info flags
    show_version: (($flags.version? | default false) or ($flags.v? | default false))
    show_info: ($flags.info? | default false)
    show_about: ($flags.about? | default false)

    # Debug and metadata flags
    debug_mode: ($flags.debug? | default false)
    metadata_mode: ($flags.metadata? | default false)
    debug_check: ($flags.xc? | default false)
    debug_remote: ($flags.xr? | default false)
    debug_log_level: ($flags.xld? | default false)

    # Operation mode flags
    check_mode: ($flags.check? | default false)
    upload_inspection: ($flags.upload? | default false)
    auto_confirm: ($flags.yes? | default false)
    wait_completion: ($flags.wait? | default false)
    keep_storage: ($flags.keepstorage? | default false)
    no_clean: ($flags.nc? | default false)
    include_notuse: ($flags.include_notuse? | default false)

    # Output and format flags
    output_format: ($flags.out? | default "")
    no_titles: ($flags.notitles? | default false)
    view_mode: ($flags.view? | default false)

    # Path and target flags
    # Only propagate --infra when explicitly passed; PWD-based detection runs in get_infra
    infra: ($flags.infra? | default "")
    infras: ($flags.infras? | default "")
    settings: ($flags.settings? | default "")
    outfile: ($flags.outfile? | default "")
    template: ($flags.template? | default "")
    select: ($flags.select? | default "")
    onsel: ($flags.onsel? | default "")
    serverpos: ($flags.serverpos? | default null)

    # New infrastructure flag
    new_infra: ($flags.new? | default "")

    # Environment flag
    environment: ($flags.environment? | default "")

    # Cache control flag
    no_cache: ($flags.no_cache? | default false)

    # Workspace dependency flags
    dep_option: ($flags.dep_option? | default "")
    dep_url: ($flags.dep_url? | default "")

    # Pack command flags
    dry_run: ($flags.dry_run? | default false)
    force: ($flags.force? | default false)
    all: ($flags.all? | default false)
    keep_latest: ($flags.keep_latest? | default null)

    # Workspace command flags
    activate: ($flags.activate? | default false)
    interactive: ($flags.interactive? | default false)
    workspace: ($flags.ws? | default ($flags.workspace? | default ""))

    # Infrastructure-from-Code flags
    pretty_print: ($flags.pretty? | default false)
    org: ($flags.org? | default "")
    apply_changes: ($flags.apply? | default false)
    verbose_output: ($flags.verbose? | default false)

    # Platform service flags
    services: ($flags.services? | default "")
  }
}

# Build standardized module arguments string
# Converts parsed flags into command-line argument string
export def build_module_args [
  flags: record
  extra: string = ""
] {
  let use_check = if $flags.check_mode { "--check " } else { "" }
  let use_upload = if ($flags.upload_inspection? | default false) { "--upload " } else { "" }
  let use_yes = if $flags.auto_confirm { "--yes " } else { "" }
  let use_wait = if $flags.wait_completion { "--wait " } else { "" }
  let use_keepstorage = if $flags.keep_storage { "--keepstorage " } else { "" }
  let use_include_notuse = if $flags.include_notuse { "--include_notuse " } else { "" }

  let str_infra = if ($flags.infra | is-not-empty) {
    $"--infra ($flags.infra) "
  } else { "" }

  let str_out = if ($flags.output_format | is-not-empty) {
    $"--out ($flags.output_format) "
  } else { "" }

  let str_outfile = if ($flags.outfile | is-not-empty) {
    $"--outfile ($flags.outfile) "
  } else { "" }

  let str_template = if ($flags.template | is-not-empty) {
    $"--template ($flags.template) "
  } else { "" }

  let str_select = if ($flags.select | is-not-empty) {
    $"--select ($flags.select) "
  } else { "" }

  let str_dep_option = if ($flags.dep_option? | default "" | is-not-empty) {
    $"--dep-option ($flags.dep_option) "
  } else { "" }

  let str_dep_url = if ($flags.dep_url? | default "" | is-not-empty) {
    $"--dep-url ($flags.dep_url) "
  } else { "" }

  let use_dry_run = if ($flags.dry_run? | default false) { "--dry-run " } else { "" }
  let use_force = if ($flags.force? | default false) { "--force " } else { "" }
  let use_all = if ($flags.all? | default false) { "--all " } else { "" }
  let str_keep_latest = if ($flags.keep_latest? | default null | is-not-empty) {
    $"--keep-latest ($flags.keep_latest) "
  } else { "" }

  let use_no_titles = if ($flags.no_titles? | default false) { "--notitles " } else { "" }
  let use_no_cache = if ($flags.no_cache? | default false) { "--no-cache " } else { "" }

  # Combine all flags with extra arguments
  # Ensure extra has trailing space if not empty
  let extra_with_space = if ($extra | is-not-empty) { $"($extra) " } else { "" }

  [
    $extra_with_space
    $str_infra
    $use_check
    $use_upload
    $use_yes
    $use_wait
    $use_keepstorage
    $str_out
    $str_outfile
    $str_template
    $str_select
    $str_dep_option
    $str_dep_url
    $use_dry_run
    $use_force
    $use_all
    $str_keep_latest
    $use_include_notuse
    $use_no_titles
    $use_no_cache
  ] | str join "" | str trim
}

# Set environment variables based on parsed flags
export def set_debug_env [flags: record] {
  let debug_mode = ($flags | get --optional debug_mode)
  if ($debug_mode | is-not-empty) and $debug_mode {
    $env.PROVISIONING_DEBUG = true
  }

  let metadata_mode = ($flags | get --optional metadata_mode)
  if ($metadata_mode | is-not-empty) and $metadata_mode {
    $env.PROVISIONING_METADATA = true
  }

  let debug_check = ($flags | get --optional debug_check)
  if ($debug_check | is-not-empty) and $debug_check {
    $env.PROVISIONING_DEBUG_CHECK = true
  }

  let debug_remote = ($flags | get --optional debug_remote)
  if ($debug_remote | is-not-empty) and $debug_remote {
    $env.PROVISIONING_DEBUG_REMOTE = true
  }

  let debug_log_level = ($flags | get --optional debug_log_level)
  if ($debug_log_level | is-not-empty) {
    $env.PROVISIONING_LOG_LEVEL = "debug"
  }

  let output_format = ($flags | get --optional output_format)
  if ($output_format | is-not-empty) {
    $env.PROVISIONING_OUT = $output_format
    $env.PROVISIONING_NO_TERMINAL = true
  }

  let environment = ($flags | get --optional environment)
  if ($environment | is-not-empty) {
    $env.PROVISIONING_ENV = $environment
  }

  # Set PROVISIONING_INFRA env var from infra flag if provided
  # This supports both direct env var and --infra flag methods
  let infra = ($flags | get --optional infra)
  if ($infra | is-not-empty) {
    $env.PROVISIONING_INFRA = $infra
  }
}

# Get debug flag for module execution
export def get_debug_flag [flags: record] {
  if $flags.debug_mode or ($env.PROVISIONING_DEBUG? | default false) {
    "-x"
  } else {
    ""
  }
}

# Extract workspace and infrastructure from workspace flag
# Handles parsing workspace:infra notation
export def extract-workspace-infra-from-flags [flags: record] {
    let ws_flag = ($flags | get --optional workspace)

    if ($ws_flag | is-empty) {
        return { workspace: null, infra: ($flags | get --optional infra) }
    }

    # Parse workspace:infra notation
    let parsed = (parse-workspace-infra-notation $ws_flag)

    {
        workspace: $parsed.workspace
        infra: (if ($parsed.infra | is-not-empty) {
            $parsed.infra
        } else {
            ($flags | get --optional infra)
        })
    }
}
