# Guide Command Handler
# Provides interactive access to guides and cheatsheets

# REMOVED: use lib_provisioning * - causes circular import (already loaded by main provisioning script)
use ../help_system.nu ["resolve-doc-url"]

# Display condensed cheatsheet summary
def display_cheatsheet_summary [] {
  print ""
  print $"(_ansi cyan_bold)╔════════════════════════════════════════════════════════════════╗(_ansi reset)"
  print $"(_ansi cyan_bold)║ (_ansi yellow_bold)📋 QUICK COMMAND REFERENCE(_ansi reset)                                     (_ansi cyan_bold)║(_ansi reset)"
  print $"(_ansi cyan_bold)╚════════════════════════════════════════════════════════════════╝(_ansi reset)"
  print ""
  print $"(_ansi yellow_bold)Infrastructure:(_ansi reset)"
  print $"  provisioning s list                      # List servers"
  print $"  provisioning s create --infra <name>     # Create servers [use --check for dry-run]"
  print $"  provisioning t list                      # List task services"
  print $"  provisioning t create kubernetes         # Install Kubernetes"
  print $"  provisioning cl list                     # List clusters"
  print ""
  print $"(_ansi yellow_bold)Workspace:(_ansi reset)"
  print $"  provisioning ws init <name>              # Initialize workspace"
  print $"  provisioning ws init <name> --infra <i>  # Init with infrastructure"
  print $"  provisioning ws init <name> --template <t># minimal, full, example"
  print $"  provisioning ws list                     # List workspaces"
  print $"  provisioning dt                          # Discover taskservs"
  print $"  provisioning discover taskservs          # Discover all taskservs"
  print $"  provisioning dp                          # Discover providers"
  print $"  provisioning dc                          # Discover clusters"
  print ""
  print $"(_ansi yellow_bold)Templates:(_ansi reset)"
  print $"  provisioning tpl list                    # List all templates"
  print $"  provisioning tpl list --type taskservs   # List taskserv templates"
  print $"  provisioning tpl show <name>             # Show template details"
  print $"  provisioning tpl apply <name> <infra>    # Apply template"
  print ""
  print $"(_ansi yellow_bold)Orchestration:(_ansi reset)"
  print $"  provisioning wf list                     # List workflows"
  print $"  provisioning wf monitor <id>             # Monitor workflow"
  print $"  provisioning bat submit <file.ncl>         # Submit batch workflow"
  print $"  provisioning orch status                 # Orchestrator status"
  print ""
  print $"(_ansi yellow_bold)Platform:(_ansi reset)"
  print $"  provisioning control-center              # Start web control center"
  print $"  provisioning mcp-server                  # Start MCP server"
  print ""
  print $"(_ansi yellow_bold)Configuration:(_ansi reset)"
  print $"  provisioning env                         # Show environment"
  print $"  provisioning val config                  # Validate configuration"
  print $"  provisioning lyr show <name>             # Show layer resolution"
  print ""
  print $"(_ansi yellow_bold)Help & Guides:(_ansi reset)"
  print $"  provisioning help                        # Main help"
  print $"  provisioning help infra                  # Infrastructure help"
  print $"  provisioning sc                          # This quick reference"
  print $"  provisioning quickstart                  # Full command cheatsheet"
  print $"  provisioning guide from-scratch          # Complete deployment guide"
  print $"  provisioning guide update                # Update guide"
  print $"  provisioning guide customize             # Customization guide"
  print ""
  print $"(_ansi yellow_bold)Common Flags:(_ansi reset)"
  print $"  --check, -c      # Dry-run mode [no changes]"
  print $"  --debug, -x      # Enable debug output"
  print $"  --yes, -y        # Auto-confirm operations"
  print $"  --infra, -i      # Specify infrastructure"
  print ""
  print $"(_ansi yellow_bold)Shortcuts Summary:(_ansi reset)"
  print $"  (_ansi cyan_bold)Infrastructure:(_ansi reset)  s=server, t=taskserv, cl=cluster, i=infra"
  print $"  (_ansi cyan_bold)Workspace:(_ansi reset)       ws=workspace, tpl=template"
  print $"  (_ansi cyan_bold)Discovery:(_ansi reset)       dt=discover taskservs, dp=providers, dc=clusters"
  print $"  (_ansi cyan_bold)Orchestration:(_ansi reset)   wf=workflow, bat=batch, orch=orchestrator"
  print $"  (_ansi cyan_bold)Config:(_ansi reset)          env, val=validate, lyr=layer"
  print $"  (_ansi cyan_bold)Utils:(_ansi reset)           ssh, sops, list=l/ls, nu"
  print $"  (_ansi cyan_bold)Help:(_ansi reset)            h=help, sc=shortcuts, guide"
  print ""
  print $"(_ansi default_dimmed)💡 Quick tips:(_ansi reset)"
  print $"(_ansi default_dimmed)   • Use 'provisioning sc' to see this reference anytime(_ansi reset)"
  print $"(_ansi default_dimmed)   • Use 'provisioning quickstart' for complete guide with examples(_ansi reset)"
  print ""
}

# Display markdown file with best available renderer
def display_markdown [file: path] {
  # Check which renderers are available
  let has_glow = (which glow | length) > 0
  let has_bat = (which bat | length) > 0
  let has_mdcat = (which mdcat | length) > 0

  # Use best available renderer (without interactive pagers - they hang with < /dev/null)
  if $has_glow {
    # glow: Beautiful markdown rendering (no --pager to avoid hanging with stdin redirected)
    ^glow $file
  } else if $has_bat {
    # bat: Good syntax highlighting (no --pager to avoid hanging)
    ^bat $file --style=auto --language=markdown
  } else if $has_mdcat {
    # mdcat: Markdown-specific renderer (no piping to less to avoid hanging)
    ^mdcat $file
  } else {
    # Fallback: Direct print with manual pagination
    let content = (open $file)
    print $content
    print ""
    print $"(_ansi yellow_bold)💡 TIP: Install a markdown renderer for better viewing(_ansi reset)"
    print ""
    print $"  (_ansi green)glow(_ansi reset) [recommended]:  brew install glow  (_ansi default_dimmed)# macOS(_ansi reset)"
    print $"                        apt install glow   (_ansi default_dimmed)# Ubuntu/Debian(_ansi reset)"
    print $"                        dnf install glow   (_ansi default_dimmed)# Fedora(_ansi reset)"
    print ""
    print $"  (_ansi green)bat(_ansi reset):                brew install bat   (_ansi default_dimmed)# macOS(_ansi reset)"
    print $"                        apt install bat    (_ansi default_dimmed)# Ubuntu/Debian(_ansi reset)"
    print ""
  }
}

# Display markdown with optional URL information
def display_markdown_with_url [file: path, doc_path: string] {
  # Show URL if configured
  let url_info = (resolve-doc-url $doc_path)
  if ($url_info.mode == "url") and ($url_info.url != null) {
    print $"📖 (_ansi cyan)Documentation: ($url_info.url)(_ansi reset)"
    print $"📁 (_ansi cyan_bold)Local file: ($url_info.local)(_ansi reset)"
    print ""
  }

  # Display guide with formatting
  display_markdown $file
}

# Main guide command dispatcher
export def handle_guide_command [
  command: string
  ops: string
  flags: record
] {
  match $command {
    "guide" | "guides" => { handle_guide $ops $flags }
    "sc" | "shortcuts" => { display_cheatsheet_summary }
    "quickstart" | "quick" => { guide_quickstart }
    "from-scratch" | "scratch" => { guide_from_scratch }
    "update" | "upgrade" => { guide_update }
    "customize" | "custom" => { guide_customize }
    "howto" => { guide_list }
    _ => {
      print $"❌ Unknown guide command: ($command)"
      print ""
      print "Available guide commands:"
      print "  guide [topic]     - Show specific guide (list, quickstart, from-scratch, update, customize)"
      print "  sc | shortcuts    - Quick command reference (FASTEST)"
      print "  quickstart | quick - Full command cheatsheet"
      print "  from-scratch | scratch - Step-by-step deployment guide"
      print "  update | upgrade  - Update existing infrastructure"
      print "  customize | custom - Customize with layers and templates"
      print "  howto             - List all guides"
      print ""
      print "Examples:"
      print "  provisioning sc"
      print "  provisioning quickstart"
      print "  provisioning from-scratch"
      print "  provisioning guide update"
      print ""
      print "Use 'provisioning help guides' for more details"
      exit 1
    }
  }
}

# Guide handler
def handle_guide [ops: string, flags: record] {
  let topic = if ($ops | is-empty) { "list" } else { $ops }

  match $topic {
    "list" => { guide_list }
    "sc" => { display_cheatsheet_summary }
    "quickstart" | "shortcuts" | "quick" => { guide_quickstart }
    "from-scratch" | "scratch" | "start" | "deploy" => { guide_from_scratch }
    "update" | "upgrade" => { guide_update }
    "customize" | "custom" | "layers" | "templates" => { guide_customize }
    _ => {
      print $"❌ Unknown guide topic: ($topic)"
      print ""
      guide_list
      exit 1
    }
  }
}

# List available guides
def guide_list [] {
  print ""
  print $"(_ansi cyan_bold)📚 AVAILABLE GUIDES(_ansi reset)"
  print ""
  print $"  (_ansi green_bold)sc(_ansi reset)           - Quick command reference (_ansi yellow_bold)[FASTEST](_ansi reset)"
  print $"  (_ansi green)quickstart(_ansi reset)   - Full command cheatsheet with examples"
  print $"  (_ansi green)from-scratch(_ansi reset) - Step-by-step guide from init to deploy"
  print $"  (_ansi green)update(_ansi reset)       - Update existing infrastructure"
  print $"  (_ansi green)customize(_ansi reset)    - Customize infrastructure with layers"
  print ""
  print $"(_ansi yellow_bold)SHORTCUTS:(_ansi reset)"
  print $"  • (_ansi cyan_bold)sc, shortcuts(_ansi reset) → Quick reference (_ansi default_dimmed)fastest, no pager(_ansi reset)"
  print $"  • (_ansi cyan)quickstart(_ansi reset) → quick"
  print $"  • (_ansi cyan)from-scratch(_ansi reset) → scratch, start, deploy"
  print $"  • (_ansi cyan)update(_ansi reset) → upgrade"
  print $"  • (_ansi cyan)customize(_ansi reset) → custom, layers, templates"
  print ""
  print $"(_ansi yellow_bold)USAGE:(_ansi reset)"
  print $"  provisioning sc                   - Quick command reference (_ansi yellow)fastest(_ansi reset)"
  print $"  provisioning shortcuts            - Same as sc"
  print $"  provisioning guide quickstart     - Full command reference"
  print $"  provisioning guide from-scratch   - Complete deployment guide"
  print $"  provisioning guide update         - Infrastructure update guide"
  print $"  provisioning guide customize      - Customization guide"
  print ""
  print $"(_ansi cyan_bold)💡 BETTER VIEWING EXPERIENCE(_ansi reset)"
  print ""
  print "  For beautifully formatted guides, install a markdown renderer:"
  print ""
  print $"  (_ansi green)glow(_ansi reset) [recommended] - Beautiful markdown rendering"
  print $"    macOS:         (_ansi cyan)brew install glow(_ansi reset)"
  print $"    Ubuntu/Debian: (_ansi cyan)apt install glow(_ansi reset)"
  print $"    Fedora:        (_ansi cyan)dnf install glow(_ansi reset)"
  print $"    Other:         (_ansi cyan)go install github.com/charmbracelet/glow@latest(_ansi reset)"
  print ""
  print $"  (_ansi green)bat(_ansi reset) - Syntax highlighting"
  print $"    macOS:         (_ansi cyan)brew install bat(_ansi reset)"
  print $"    Ubuntu/Debian: (_ansi cyan)apt install bat(_ansi reset)"
  print ""
  print $"  (_ansi default_dimmed)Without a renderer, guides display as plain text with pagination.(_ansi reset)"
  print ""
  print $"(_ansi yellow_bold)💡 All guides provide copy-paste ready commands(_ansi reset)"
  print ""
}

# Display quickstart cheatsheet
def guide_quickstart [] {
  let guide_file = "provisioning/docs/src/guides/quickstart-cheatsheet.md"

  if not ($guide_file | path exists) {
    print $"❌ Guide file not found: ($guide_file)"
    print $"   Expected location: ($env.PWD)/($guide_file)"
    exit 1
  }

  # Display guide with formatting
  print ""
  print ""
  print $"(_ansi cyan_bold)═══════════════════════════════════════════════════════════════(_ansi reset)"
  print $"(_ansi cyan_bold) (_ansi yellow_bold)📚 QUICK COMMAND CHEATSHEET(_ansi reset)"
  print $"(_ansi cyan_bold)═══════════════════════════════════════════════════════════════(_ansi reset)"
  print ""

  # Display guide with URL information and markdown rendering
  display_markdown_with_url $guide_file "guides/quickstart-cheatsheet"

  print ""
  print $"(_ansi green_bold)✅ Cheatsheet displayed(_ansi reset)"
  print ""
  print $"(_ansi yellow)Other guides:(_ansi reset)"
  print $"  • provisioning guide from-scratch"
  print $"  • provisioning guide update"
  print $"  • provisioning guide customize"

  # Show cheatsheet summary
  display_cheatsheet_summary
}

# Display from-scratch guide
def guide_from_scratch [] {
  let guide_file = "provisioning/docs/src/guides/from-scratch.md"

  if not ($guide_file | path exists) {
    print $"❌ Guide file not found: ($guide_file)"
    print $"   Expected location: ($env.PWD)/($guide_file)"
    exit 1
  }

  # Display guide with formatting
  print ""
  print $"(_ansi green_bold)═══════════════════════════════════════════════════════════════(_ansi reset)"
  print $"(_ansi green_bold)║ (_ansi yellow_bold)🚀 FROM SCRATCH: COMPLETE INFRASTRUCTURE DEPLOYMENT(_ansi reset)      (_ansi green_bold)║(_ansi reset)"
  print $"(_ansi green_bold)═══════════════════════════════════════════════════════════════(_ansi reset)"
  print ""

  # Display guide with URL information and markdown rendering
  display_markdown_with_url $guide_file "guides/from-scratch"

  print ""
  print $"(_ansi green_bold)✅ Guide displayed(_ansi reset)"
  print ""
  print $"(_ansi yellow)Other guides:(_ansi reset)"
  print $"  • provisioning guide quickstart"
  print $"  • provisioning guide update"
  print $"  • provisioning guide customize"

  # Show cheatsheet summary
  display_cheatsheet_summary
}

# Display update guide
def guide_update [] {
  let guide_file = "provisioning/docs/src/guides/update-infrastructure.md"

  if not ($guide_file | path exists) {
    print $"❌ Guide file not found: ($guide_file)"
    print $"   Expected location: ($env.PWD)/($guide_file)"
    exit 1
  }

  # Display guide with formatting
  print ""
  print $"(_ansi blue_bold)═══════════════════════════════════════════════════════════════(_ansi reset)"
  print $"(_ansi blue_bold)║ (_ansi yellow_bold)🔄 UPDATE EXISTING INFRASTRUCTURE(_ansi reset)                          (_ansi blue_bold)║(_ansi reset)"
  print $"(_ansi blue_bold)═══════════════════════════════════════════════════════════════(_ansi reset)"
  print ""

  # Display guide with URL information and markdown rendering
  display_markdown_with_url $guide_file "guides/update-infrastructure"

  print ""
  print $"(_ansi green_bold)✅ Guide displayed(_ansi reset)"
  print ""
  print $"(_ansi yellow)Other guides:(_ansi reset)"
  print $"  • provisioning guide quickstart"
  print $"  • provisioning guide from-scratch"
  print $"  • provisioning guide customize"

  # Show cheatsheet summary
  display_cheatsheet_summary
}

# Display customize guide
def guide_customize [] {
  let guide_file = "provisioning/docs/src/guides/customize-infrastructure.md"

  if not ($guide_file | path exists) {
    print $"❌ Guide file not found: ($guide_file)"
    print $"   Expected location: ($env.PWD)/($guide_file)"
    exit 1
  }

  # Display guide with formatting
  print ""
  print $"(_ansi purple_bold)═══════════════════════════════════════════════════════════════(_ansi reset)"
  print $"(_ansi purple_bold)║ (_ansi yellow_bold)🎨 CUSTOMIZE INFRASTRUCTURE(_ansi reset)                               (_ansi purple_bold)║(_ansi reset)"
  print $"(_ansi purple_bold)═══════════════════════════════════════════════════════════════(_ansi reset)"
  print ""

  # Display guide with URL information and markdown rendering
  display_markdown_with_url $guide_file "guides/customize-infrastructure"

  print ""
  print $"(_ansi green_bold)✅ Guide displayed(_ansi reset)"
  print ""
  print $"(_ansi yellow)Other guides:(_ansi reset)"
  print $"  • provisioning guide quickstart"
  print $"  • provisioning guide from-scratch"
  print $"  • provisioning guide update"

  # Show cheatsheet summary
  display_cheatsheet_summary
}
