import { Flow, Elb } from '@walkeros/core';
import { BuildOptions as BuildOptions$1 } from 'esbuild';

/**
 * CLI Build Configuration
 *
 * Build-time options for the walkerOS CLI bundle generation.
 * Completely separate from Flow.Config (runtime configuration).
 *
 * @packageDocumentation
 */

/**
 * Build options for bundle generation.
 *
 * @remarks
 * Contains all CLI-specific build settings including:
 * - Package management (NPM packages to bundle)
 * - Code injection (custom user code)
 * - Output configuration (file paths, formats)
 * - Esbuild settings (minification, source maps, etc.)
 *
 * Completely separate from Flow.Config which handles runtime event processing.
 */
interface BuildOptions extends Pick<BuildOptions$1, 'format' | 'target' | 'minify' | 'sourcemap' | 'platform' | 'external'> {
    /**
     * NPM packages to bundle.
     *
     * @remarks
     * Maps package name to version and imports configuration.
     * Packages are downloaded from npm and bundled into the output.
     *
     * @example
     * ```json
     * {
     *   "@walkeros/core": {
     *     "version": "^0.2.0",
     *     "imports": ["getId", "tryCatch"]
     *   }
     * }
     * ```
     */
    packages: Record<string, {
        version?: string;
        imports?: string[];
    }>;
    /**
     * User code to include in bundle.
     *
     * @remarks
     * Optional custom JavaScript/TypeScript code that will be included in the bundle.
     * Can reference imported packages and will be executed when bundle loads.
     * If omitted, the template's default behavior will be used.
     *
     * @default ""
     *
     * @example
     * ```typescript
     * "export default () => startFlow({ sources: {...}, destinations: {...} })"
     * ```
     */
    code?: string;
    /**
     * Output file path.
     *
     * @remarks
     * Absolute or relative path for the generated bundle.
     * Directory will be created if it doesn't exist.
     *
     * @default "./dist/walker.js" (web) or "./dist/bundle.js" (server)
     *
     * @example
     * "./dist/walker.min.js"
     */
    output: string;
    /**
     * Temporary directory for build artifacts.
     *
     * @remarks
     * Used for:
     * - Downloaded packages
     * - Generated entry points
     * - Intermediate build files
     *
     * Cleaned up after successful build unless shared with simulator.
     *
     * @default ".tmp"
     */
    tempDir?: string;
    /**
     * Custom template file path.
     *
     * @remarks
     * Override the default template (base.hbs or server.hbs).
     * Template receives variables: {{sources}}, {{destinations}}, {{collector}}, {{{CODE}}}
     *
     * @default undefined (uses platform-specific default)
     *
     * @example
     * "./templates/custom.hbs"
     */
    template?: string;
    /**
     * Enable package caching.
     *
     * @remarks
     * When enabled, downloaded packages are cached for faster subsequent builds.
     *
     * @default true
     */
    cache?: boolean;
    /**
     * Minification options.
     *
     * @remarks
     * Fine-tune minification behavior.
     * Only applies when minify=true.
     */
    minifyOptions?: MinifyOptions;
    /**
     * Window property name for collector instance (web platform only).
     *
     * @remarks
     * Only used when platform=browser and format=iife.
     * The collector instance will be assigned to window[windowCollector].
     * Ignored for server platform.
     *
     * @default "collector"
     *
     * @example
     * ```json
     * {
     *   "build": {
     *     "windowCollector": "tracker",
     *     "windowElb": "track"
     *   }
     * }
     * ```
     *
     * Results in: `window.tracker = collector; window.track = elb;`
     */
    windowCollector?: string;
    /**
     * Window property name for elb function (web platform only).
     *
     * @remarks
     * Only used when platform=browser and format=iife.
     * The elb function will be assigned to window[windowElb].
     * Ignored for server platform.
     *
     * @default "elb"
     */
    windowElb?: string;
}
/**
 * Minification options.
 *
 * @remarks
 * Controls esbuild's minification behavior.
 */
interface MinifyOptions {
    /**
     * Minify identifiers (variable names).
     *
     * @default true
     */
    identifiers?: boolean;
    /**
     * Minify syntax (shorten code).
     *
     * @default true
     */
    syntax?: boolean;
    /**
     * Minify whitespace.
     *
     * @default true
     */
    whitespace?: boolean;
    /**
     * Keep original function/class names.
     *
     * @remarks
     * Useful for debugging production bundles.
     *
     * @default false
     */
    keepNames?: boolean;
    /**
     * How to handle legal comments.
     *
     * @default "none"
     */
    legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external';
}
/**
 * Single environment configuration.
 *
 * @remarks
 * Combines Flow.Config (runtime) with BuildOptions (build-time).
 * This is the structure stored in config files for each environment.
 */
interface EnvironmentConfig {
    /**
     * Runtime event processing configuration.
     *
     * @remarks
     * Defines sources, destinations, collector settings.
     * From @walkeros/core - platform-agnostic.
     */
    flow: Flow.Config;
    /**
     * Build-time configuration.
     *
     * @remarks
     * Defines how to bundle the flow configuration.
     * CLI-specific settings.
     */
    build: BuildOptions;
}
/**
 * Multi-environment setup configuration.
 *
 * @remarks
 * Top-level config file format supporting multiple deployment environments.
 * Each environment has separate flow and build configurations.
 *
 * @example
 * ```json
 * {
 *   "version": 1,
 *   "variables": {
 *     "GA_ID": "G-XXXXXXXXXX"
 *   },
 *   "environments": {
 *     "production": {
 *       "flow": { "platform": "web", ... },
 *       "build": { "packages": {...}, "output": "./dist/prod.js" }
 *     },
 *     "staging": {
 *       "flow": { "platform": "web", ... },
 *       "build": { "packages": {...}, "output": "./dist/staging.js" }
 *     }
 *   }
 * }
 * ```
 */
interface Setup {
    /**
     * Configuration schema version.
     */
    version: 1;
    /**
     * JSON Schema reference for IDE validation.
     */
    $schema?: string;
    /**
     * Shared variables for interpolation across all environments.
     */
    variables?: Record<string, string | number | boolean>;
    /**
     * Reusable configuration definitions.
     */
    definitions?: Record<string, unknown>;
    /**
     * Environments with flow and build configurations.
     */
    environments: Record<string, EnvironmentConfig>;
}

/**
 * Global CLI Options
 *
 * Options that apply to all commands.
 */
/**
 * Global options available across all CLI commands
 */
interface GlobalOptions {
    /**
     * Execute using local Node.js environment (vs Docker container)
     * @default false (Docker mode)
     */
    local?: boolean;
    /**
     * Show detailed execution logs
     * @default false
     */
    verbose?: boolean;
    /**
     * Suppress all output except errors
     * @default false
     */
    silent?: boolean;
    /**
     * Preview command without executing
     * @default false
     */
    dryRun?: boolean;
}

interface BundleStats {
    totalSize: number;
    packages: {
        name: string;
        size: number;
    }[];
    buildTime: number;
    treeshakingEffective: boolean;
}

interface BundleCommandOptions extends GlobalOptions {
    config: string;
    env?: string;
    all?: boolean;
    stats?: boolean;
    json?: boolean;
    cache?: boolean;
}
declare function bundleCommand(options: BundleCommandOptions): Promise<void>;
/**
 * High-level bundle function for programmatic usage.
 *
 * Handles configuration loading, parsing, and logger creation internally.
 *
 * @param configOrPath - Bundle configuration object or path to config file
 * @param options - Bundle options
 * @param options.silent - Suppress all output (default: false)
 * @param options.verbose - Enable verbose logging (default: false)
 * @param options.stats - Collect and return bundle statistics (default: false)
 * @param options.cache - Enable package caching (default: true)
 * @returns Bundle statistics if stats option is true, otherwise void
 *
 * @example
 * ```typescript
 * // With config object
 * await bundle({
 *   platform: 'web',
 *   packages: { '@walkeros/collector': { imports: ['startFlow'] } },
 *   sources: { browser: { code: 'sourceBrowser' } },
 *   destinations: { api: { code: 'destinationApi' } },
 *   code: 'export default startFlow({ sources, destinations })',
 *   output: './dist/walker.js'
 * });
 *
 * // With config file
 * await bundle('./walker.config.json', { stats: true });
 * ```
 */
declare function bundle(configOrPath: unknown, options?: {
    silent?: boolean;
    verbose?: boolean;
    stats?: boolean;
    cache?: boolean;
}): Promise<BundleStats | void>;

/**
 * Call Tracker for Simulation
 *
 * Wraps mock environment functions to track API calls.
 * Used with destination-provided examples/env.ts mocks.
 */
interface ApiCall {
    type: 'call';
    path: string;
    args: unknown[];
    timestamp: number;
}

interface SimulateCommandOptions extends GlobalOptions {
    config: string;
    event?: string;
    json?: boolean;
}
interface SimulationResult {
    success: boolean;
    error?: string;
    collector?: unknown;
    elbResult?: Elb.PushResult;
    logs?: unknown[];
    usage?: Record<string, ApiCall[]>;
    duration?: number;
}

/**
 * CLI command handler for simulate command
 */
declare function simulateCommand(options: SimulateCommandOptions): Promise<void>;
/**
 * High-level simulate function for programmatic usage.
 *
 * Handles configuration loading internally and returns structured results.
 *
 * @param configOrPath - Bundle configuration object or path to config file
 * @param event - Event object to simulate
 * @param options - Simulation options
 * @param options.silent - Suppress all output (default: false)
 * @param options.verbose - Enable verbose logging (default: false)
 * @param options.json - Format output as JSON (default: false)
 * @returns Simulation result with success status, elb result, and usage data
 *
 * @example
 * ```typescript
 * // With config file
 * const result = await simulate('./walker.config.json', {
 *   name: 'page view',
 *   data: { title: 'Home Page', path: '/', url: 'https://example.com' }
 * });
 *
 * // With config object
 * const result = await simulate(
 *   {
 *     platform: 'web',
 *     packages: { '@walkeros/collector': { imports: ['startFlow'] } },
 *     code: '...',
 *     output: './bundle.js'
 *   },
 *   { name: 'page view' },
 *   { silent: true }
 * );
 * ```
 */
declare function simulate(configOrPath: string | unknown, event: unknown, options?: {
    silent?: boolean;
    verbose?: boolean;
    json?: boolean;
}): Promise<SimulationResult>;

/**
 * Push command options
 */
interface PushCommandOptions extends GlobalOptions {
    config: string;
    event: string;
    env?: string;
    json?: boolean;
}

/**
 * CLI command handler for push command
 */
declare function pushCommand(options: PushCommandOptions): Promise<void>;

/**
 * Run Command Types
 *
 * Types for running walkerOS flows via CLI using @walkeros/docker as a library
 */

/**
 * Run mode - determines which execution mode to use
 */
type RunMode = 'collect' | 'serve';
/**
 * CLI command options for `walkeros run`
 */
interface RunCommandOptions extends GlobalOptions {
    /** Flow configuration file path (.json or pre-built .mjs) */
    config: string;
    /** Server port (overrides flow config) */
    port?: number;
    /** Server host (default: 0.0.0.0) */
    host?: string;
    /** Serve path (URL directory path, e.g., 'libs/v1') */
    servePath?: string;
    /** Serve name (filename in URL, default: walker.js) */
    serveName?: string;
    /** Enable JSON output */
    json?: boolean;
}
/**
 * Programmatic run options (subset of CLI options)
 */
interface RunOptions {
    /** Flow configuration file path (.json or pre-built .mjs) */
    config: string | unknown;
    /** Server port */
    port?: number;
    /** Server host */
    host?: string;
    /** Serve path (URL directory path, e.g., 'libs/v1') */
    servePath?: string;
    /** Serve name (filename in URL, default: walker.js) */
    serveName?: string;
    /** Suppress output */
    silent?: boolean;
    /** Verbose logging */
    verbose?: boolean;
}
/**
 * Result from running a flow
 */
interface RunResult {
    /** Whether the flow ran successfully */
    success: boolean;
    /** Exit code */
    exitCode: number;
    /** Error message if failed */
    error?: string;
    /** Execution duration in milliseconds */
    duration: number;
}

/**
 * Run Command
 *
 * Runs walkerOS flows using @walkeros/docker as a library
 * No Docker daemon required - runs directly in Node.js
 */

/**
 * CLI command function for `walkeros run`
 *
 * @param mode - Run mode (collect | serve)
 * @param options - Command options
 */
declare function runCommand(mode: string, options: RunCommandOptions): Promise<void>;
/**
 * Programmatic run function
 *
 * @param mode - Run mode (collect | serve)
 * @param options - Run options
 * @returns Run result
 *
 * @example
 * ```typescript
 * // Run with JSON config (bundles automatically)
 * await run('collect', {
 *   config: './flow.json',
 *   port: 8080
 * });
 *
 * // Run with pre-built bundle
 * await run('collect', {
 *   config: './flow.mjs',
 *   port: 8080
 * });
 * ```
 */
declare function run(mode: RunMode, options: RunOptions): Promise<RunResult>;

/**
 * Template Configuration Types
 *
 * Type definitions for template processing and serialization.
 * Used by the template engine and serializer.
 *
 * @packageDocumentation
 */
/**
 * Source or Destination configuration item for templates.
 *
 * @remarks
 * This type is used in template processing where config objects
 * are serialized to JavaScript code.
 */
interface SourceDestinationItem {
    /**
     * JavaScript code reference (variable name or expression)
     */
    code: string;
    /**
     * Configuration object for the source/destination
     */
    config?: unknown;
    /**
     * Environment-specific variables
     */
    env?: unknown;
    /**
     * Allow additional properties for extensibility
     */
    [key: string]: unknown;
}
/**
 * Template variables that can be used in Handlebars templates.
 *
 * @remarks
 * These variables are available in template files for customization.
 */
interface TemplateVariables {
    /**
     * Serialized sources configuration
     */
    sources: string;
    /**
     * Serialized destinations configuration
     */
    destinations: string;
    /**
     * Serialized collector configuration
     */
    collector: string;
    /**
     * User-provided code to be inserted
     */
    CODE: string;
    /**
     * Build configuration (optional)
     */
    build?: Record<string, unknown>;
}
/**
 * Processed template variables after serialization.
 *
 * @remarks
 * Internal type used by the serializer to represent processed configs.
 */
interface ProcessedTemplateVariables {
    /**
     * Processed sources with serialized configs
     */
    sources?: Record<string, TemplateSource>;
    /**
     * Processed destinations with serialized configs
     */
    destinations?: Record<string, TemplateDestination>;
    /**
     * Processed collector configuration
     */
    collector?: Record<string, unknown> | string;
    /**
     * Allow additional properties
     */
    [key: string]: unknown;
}
/**
 * Template source after processing.
 *
 * @internal
 */
interface TemplateSource {
    code: string;
    config?: unknown | string;
    env?: unknown;
    [key: string]: unknown;
}
/**
 * Template destination after processing.
 *
 * @internal
 */
interface TemplateDestination {
    code: string;
    config?: unknown | string;
    env?: unknown;
    [key: string]: unknown;
}

export { type BuildOptions, type BundleStats, type EnvironmentConfig, type GlobalOptions, type ProcessedTemplateVariables, type RunCommandOptions, type RunMode, type RunOptions, type RunResult, type Setup, type SimulationResult, type SourceDestinationItem, type TemplateDestination, type TemplateSource, type TemplateVariables, bundle, bundleCommand, pushCommand, run, runCommand, simulate, simulateCommand };
