#!/usr/bin/env node
/**
 * msger CLI - uses universal CLI from msgcommon
 */
import { runCli } from '@bobfrankston/msgcommon';
import { showMessageBox } from './shower.js';
import packageJson from './package.json' with { type: 'json' };
import path from 'path';
const HELP_TEXT = `
msger v${packageJson.version} - Fast, lightweight, cross-platform message box (Rust-powered)

Usage:
  msger [options] [message words...]
  msger -message "Your message"
  echo '{"message":"text"}' | msger

Options:
  -message <text>         Specify message text (use quotes for multi-word)
                          Supports ANSI color escape sequences (e.g., \\x1b[31mRed\\x1b[0m)
  -title <text>           Set window title
  -html <html>            Display HTML formatted message (inline)
  -htmlfrom <file|url>    Fetch HTML from file/URL and embed in template (has buttons & msger API)
  -url <url>              Load URL directly in webview (no template, no buttons)
  -hash <fragment>        Hash fragment to append to URL (requires -url). Leading # optional.
  -buttons <label...>     Specify button labels (e.g., -buttons Yes No Cancel)
  -ok                     Add OK button
  -cancel                 Add Cancel button
  -input [placeholder]    Include an input field with optional placeholder text
  -default <text>         Default value for input field
  -size <width,height>    Set window size (e.g., -size 800,600)
  -zoom <percent>         Set zoom level as percentage (e.g., -zoom 150 for 150%)
  -pos <x,y>              Set window position (e.g., -pos 100,200)
  -screen <number>        [Windows only] Screen index for multi-monitor (0=primary, 1=second, etc.)
  -icon <path>            Set window icon (PNG file). Default: icon.png in current directory
  -timeout <seconds>      Auto-close after specified seconds
  -detach                 Leave window open after app exits (parent process returns immediately)
  -fullscreen             Start window in fullscreen mode (F11 to toggle, Escape to exit)
  -no-escape-closes       Prevent Escape key from closing window (still exits fullscreen)
  -reset                  Clear localStorage on startup (useful for resetting web content state)
  -ontop                  Keep window always on top of other windows
  -load <file>            Load options from JSON file (supports comments)
  -save <file>            Save current options to JSON file
  -noshow                 Don't display the window. With -save, also exits after saving.
                          Otherwise the WebView still loads and runs scripts (so a page can
                          query the DOM/CSS and post a result via window.ipc.postMessage)
                          — only the window isn't mapped on screen. Useful for headless
                          CSS/JS resolution (e.g. contrast-color, getComputedStyle).
  -pin                    Create pinnable Start Menu shortcut (requires -load)
  -dev                    Open DevTools (F12) automatically on startup (for debugging)
  -debug                  Return debug info (HTML, size) in result
  -noresult               Suppress JSON result output on stdout (errors still go to stderr)
  -result [fieldname]     Re-enable result output (overrides -noresult from a config file).
                          With <fieldname>, print just that field's value (e.g. -result value
                          prints only result.value, no JSON wrapper). Strings print as-is;
                          other types JSON-stringify. Missing field → exit 2.
  -v, -version, --version Show version number (alone: print and exit; with options: show in title)
  -help, -?, --help       Show this help message

Examples:
  msger Hello World
  msger -message "Save changes?" -buttons Yes No Cancel
  msger -message "Enter your name:" -input "Your name" -default "John Doe"
  msger -html "<h1>Title</h1><p>Formatted content</p>"
  msger -htmlfrom page.html -buttons OK Cancel
  msger -htmlfrom "https://example.com" -buttons OK
  msger -url "https://example.com"
  msger -url "https://example.com" -hash section1
  msger -url "https://example.com" -detach
  msger -title "Alert" -message "Operation complete"
  echo -e "\\x1b[31mError:\\x1b[0m Something failed" | msger
  echo '{"message":"Test","buttons":["OK"]}' | msger

  # Headless evaluation — use the WebView as a CSS/JS engine, no UI
  msger -noshow -html "<div id=x style='color:contrast-color(steelblue)'></div><script>requestAnimationFrame(()=>requestAnimationFrame(()=>window.ipc.postMessage(JSON.stringify({button:'x',value:getComputedStyle(document.getElementById('x')).color}))))</script>" -result value

Notes:
  - If no options are provided, all non-option arguments are concatenated as the message
  - Message text supports ANSI color codes (automatically converted to HTML)
  - Press ESC to dismiss the dialog (returns button: "dismissed")
  - Press Enter to click the last (default) button
  - Default button is OK if no buttons specified
  - Much faster than Electron-based msgview (~50-200ms vs ~2-3s startup)

Security Note:
  - msger is designed for displaying trusted, friendly content (local apps, your own HTML)
  - It is NOT a secure sandbox for untrusted/hostile web content
  - Use -htmlfrom and -url with trusted sources only
`;
await runCli({
    appName: 'msger',
    version: packageJson.version,
    helpText: HELP_TEXT,
    showMessage: showMessageBox,
    cliPath: path.join(import.meta.dirname, 'cli.js')
});
