#compdef loki

function _loki {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C \
        '1: :_loki_commands' \
        '*::arg:->args'

    case $state in
        (args)
            case $line[1] in
                start|quick)
                    _loki_start
                    ;;
                council)
                    _loki_council
                    ;;
                compound)
                    _loki_compound
                    ;;
                provider)
                    _loki_provider
                    ;;
                memory)
                    _loki_memory
                    ;;
                plan)
                    _loki_plan
                    ;;
                export)
                    _arguments '--sarif[Write findings.sarif for a run]'
                    ;;
                tour)
                    _arguments '--live[Tiny real task, same as loki wow]'
                    ;;
                wow)
                    _arguments \
                        '--offline[Always show the offline sample]' \
                        '--dry-run[Print the plan, no model call]' \
                        '--keep[Keep the temp repo]' \
                        '--provider[Provider]:provider:(claude opencode)' \
                        '--max-cost[Hard per-run cap in USD]:usd:'
                    ;;
                try)
                    _arguments \
                        '--dry-run[Clone, print the task and estimate, no model call]' \
                        '--provider[Provider]:provider:(claude opencode)' \
                        '--max-cost[Hard per-run cap in USD]:usd:'
                    ;;
                control)
                    _arguments \
                        '--port[Port for the control plane server]:port:' \
                        '--json[Output as JSON]' \
                        '--repo[Repository to backfill]:repo:_files -/' \
                        '1:subcommand:(open serve stop status help)'
                    ;;
                config)
                    _loki_config
                    ;;
                dashboard)
                    _loki_dashboard
                    ;;
                sandbox)
                    _loki_sandbox
                    ;;
                notify)
                    _loki_notify
                    ;;
                enterprise)
                    _loki_enterprise
                    ;;
                projects)
                    _loki_projects
                    ;;
                telemetry)
                    _loki_telemetry
                    ;;
                agent)
                    _loki_agent
                    ;;
                cost)
                    _arguments \
                        '--json[Output machine-readable JSON]' \
                        '--last[Show only the last N runs]:count:' \
                        '--month[Only runs generated in that month]:month (YYYY-MM):' \
                        '--csv[One CSV row per run]' \
                        '--detail[Per-iteration cache and trend breakdown]' \
                        '--help[Show help]'
                    ;;
                next)
                    _arguments \
                        '--yes[Skip the confirmation prompt]' \
                        '--dry-run[Show what would run without running it]' \
                        '--suggest[With no active run, propose up to 3 small tasks]' \
                        '--json[Output machine-readable JSON]' \
                        '--help[Show help]'
                    ;;
                estimate)
                    _arguments \
                        '--json[Output machine-readable JSON]' \
                        '--model[Model whose first-run prior to use]:model:' \
                        '--provider[Provider whose default model is used]:provider:' \
                        '--help[Show help]'
                    ;;
                status)
                    _arguments \
                        '--json[Output machine-readable JSON]' \
                        '--badge[Print verified deploy badge]' \
                        '--probe[Re-probe last deploy health URL]' \
                        '--follow[Print one line per run event until the run ends]' \
                        '--help[Show help]'
                    ;;
                doctor)
                    _arguments \
                        '--json[Output machine-readable JSON]' \
                        '(-q --quiet)'{-q,--quiet}'[Print only failed and warned checks plus the summary]' \
                        '--fix[Create state dirs and a default config; offer claude install and login]' \
                        '--yes[With --fix: run the claude install and login without asking]' \
                        '--help[Show help]'
                    ;;
                chat)
                    _arguments \
                        '--attach[Attach to a running session]' \
                        '--tui[Use the terminal UI]' \
                        '--help[Show help]'
                    ;;
                agents)
                    _arguments \
                        '1:subcommand:(list new show export)' \
                        '--claude[Export to .claude/agents]' \
                        '--user[Use the user-level agents directory]' \
                        '--help[Show help]'
                    ;;
                models)
                    _arguments \
                        '--local[Show local models]' \
                        '--json[Output machine-readable JSON]' \
                        '--help[Show help]'
                    ;;
                setup)
                    _arguments \
                        '--yes[Non-interactive defaults]' \
                        '--check[Report only]' \
                        '--help[Show help]'
                    ;;
                route)
                    _arguments \
                        '1:verb:(start quick)' \
                        '--json[Output machine-readable JSON]' \
                        '--provider[AI provider]:provider name:(claude opencode)' \
                        '--model[Model or route override]:model:' \
                        '--no-pr[Skip the pull request]' \
                        '--max-cost[Spend cap in USD]:amount:' \
                        '--help[Show help]'
                    ;;
                edit)
                    _arguments \
                        '--verify[Run verification after the edit]' \
                        '--commit[Commit the edit]' \
                        '--dry-run[Describe the change only]' \
                        '--help[Show help]' \
                        '*:file:_files'
                    ;;
                reset)
                    _loki_reset
                    ;;
                logs)
                    _arguments \
                        '--follow[Follow logs in real-time]' \
                        '-f[Follow logs in real-time]' \
                        '--tail[Number of lines to show]:number:' \
                        '-n[Number of lines to show]:number:' \
                        '--all[Show all lines]' \
                        '-a[Show all lines]' \
                        '--help[Show help]' \
                        '-h[Show help]'
                    ;;
                issue)
                    _loki_issue
                    ;;
                metrics)
                    _arguments \
                        '--json[Machine-readable JSON output]' \
                        '--last[Analyze last N sessions]:number:' \
                        '--save[Write report to METRICS.md]' \
                        '--share[Upload report as a secret GitHub Gist]' \
                        '--public[With --share, create a PUBLIC gist]' \
                        '--help[Show help]' \
                        '1:subcommand:(prometheus)'
                    ;;
                report)
                    _arguments \
                        '--json[Machine-readable JSON output]' \
                        '--since[Window for kpis (Nd or YYYY-MM-DD)]:since:' \
                        '--efficiency[Include efficiency totals]' \
                        '--help[Show help]' \
                        '1:subcommand:(session metrics cost kpis export share dogfood release-notes)'
                    ;;
                share)
                    _arguments \
                        '--public[Create a PUBLIC gist, visible to anyone with the URL]' \
                        '--private[Create a secret gist (default)]' \
                        '--format[Report format]:format:(text markdown html)' \
                        '--help[Show help]'
                    ;;
                proof)
                    _arguments \
                        '--yes[Skip redaction-preview confirmation]' \
                        '--public[Create a PUBLIC gist when sharing]' \
                        '--private[Create a secret gist when sharing (default)]' \
                        '--hosted[Hosted publishing (coming in R9)]' \
                        '--dry-run[Scan and list what share would publish; publishes nothing]' \
                        '--help[Show help]' \
                        '1:subcommand:(list show open share badge md bundle)'
                    ;;
                completions)
                    _arguments '1:shell:(bash zsh install)'
                    ;;
                version)
                    _arguments '--json[Print version, runtime and install path as JSON]' '--help[Show help]'
                    ;;
                monitor)
                    _directories
                    ;;
                context|ctx)
                    _loki_context
                    ;;
                code)
                    _loki_code
                    ;;
                github)
                    _arguments \
                        '1:subcommand:(status sync export pr publish protect)' \
                        '--dry-run[protect: show the branch-protection read, change nothing]' \
                        '--off[protect: restore the saved branch protection]' \
                        '--public[publish: create a public repository]' \
                        '--private[publish: create a private repository]' \
                        '--dir[publish: project directory]:directory:_directories'
                    ;;
                deploy)
                    _arguments \
                        '--dir[Project directory to scan]:directory:_directories' \
                        '--no-clip[Do not copy the command to the clipboard]' \
                        '--execute[Run the deploy command if the receipt gate passes]' \
                        '--canary[With --execute: staged rollout (Vercel promote, Fly canary)]' \
                        '--env-file[With --execute: push KEY=VALUE env via Vercel, Fly, Netlify or Cloudflare (names-only record)]:env file:_files' \
                        '--domain[With --execute: attach a custom domain and prove TLS with openssl]:hostname:' \
                        '--allow-unanchored[Proceed when the receipt records no baseline]' \
                        '--health-url[Health probe URL]:url:' \
                        '--auto-rollback[Roll back on a failed health probe]' \
                        '--help[Show help]'
                    ;;
                verify-pr)
                    _arguments \
                        '--out[Result directory]:dir:_files -/' \
                        '--json[Print the verdict object on stdout]' \
                        '--help[Show help]'
                    ;;
                verify)
                    _arguments \
                        '--pubkey[Check against this public key only]:key file:_files' \
                        '--sign-deploy[Sign a loki.deploy/1 deploy record in place]:record:_files' \
                        '--sign-provenance[Sign a loki.provenance/1 doc in place]:doc:_files' \
                        '--url[Verify the live provenance doc served at URL]:url:' \
                        '--expect-sha[Require the provenance head_sha to equal SHA]:sha:' \
                        '--receipt[Cited receipt file for a deploy record]:receipt:_files' \
                        '--max-age[Reject a receipt older than DUR]:duration:' \
                        '--require-exogenous[Exit 4 when a VERIFIED receipt has no agent-independent passing check]' \
                        '--explain[List each gate as exogenous or agent-influenced with the evidence it read]' \
                        '--json[Print the verdict and gates as JSON on stdout]' \
                        '--seal-composite[Sign a workspace composite]:run dir:_directories' \
                        '--fast[Deterministic checks only: no model call, no network]' \
                        '--path[With --fast: repo root to check]:dir:_directories' \
                        '--diff-base[With --fast: scope the checks to the diff against REF]:ref:' \
                        '--no-cache[With --fast: ignore the result cache]' \
                        '--help[Show help]' \
                        '*:receipt or deploy record:_files'
                    ;;
            esac
            ;;
    esac
}

function _loki_commands {
    local -a commands
    commands=(
        'start:Build from a goal, a PRD file or an issue'
        'chat:Talk it through; --attach joins the running build'
        'status:What is running, how it ended, what to do next'
        'verify:Deterministic verification with CI exit codes'
        'receipt:The signed proof of a run'
        'stop:Stop the running build'
        'undo:Plan or apply an undo of a run'
        'deploy:Deploy a VERIFIED run'
        'doctor:Check and repair your setup'
        'config:Show or change settings'
        'control:The local UI (Control Plane)'
    )
    _describe -t commands 'loki command' commands
}

function _loki_start {
    # Rule: list every flag bin/loki routes (Bun/engine10 ones such as --model, --max-cost, --spec, --no-pr too), not only cmd_start's own.
    _arguments \
        '--provider[AI provider]:provider name:(claude opencode)' \
        '--parallel[Parallel mode]' \
        '--brief[Zero-config brief mode]:brief text:' \
        '--worktree[Git worktree isolation]' \
        '--pr[Worktree plus auto-create PR]' \
        '--ship[Worktree plus PR plus auto-merge]' \
        '--detach[Run in background (implies --worktree)]' \
        '--workspace[Run a loki.yaml workspace for the brief]:workspace name:' \
        '--deploy[Deploy after a VERIFIED run via loki deploy --execute]' \
        '--health-url[With --deploy: health probe URL]:url:' \
        '--auto-rollback[With --deploy: roll back on a failed health probe]' \
        '--destination[With --deploy: preview, staging or production]:destination:(preview staging production)' \
        '--canary[With --deploy: canary rollout]' \
        '--domain[With --deploy: attach this domain and prove TLS]:hostname:' \
        '--env-file[With --deploy: env file pushed to the provider]:file:_files' \
        '--background[Background mode]' \
        '--bg[Background mode]' \
        '--simple[Force simple complexity]' \
        '--complex[Force complex complexity]' \
        '--github[Enable GitHub issue import]' \
        '--no-dashboard[Disable web dashboard]' \
        '--sandbox[Run in Docker sandbox]' \
        '--skip-memory[Skip loading memory context]' \
        '--spec[Run against an edited spec file]:spec file:_files' \
        '--spec-first[Write an editable spec, then stop]' \
        '--dry-run[Validate flags and preflight, print provider, model and cap, spend nothing]' \
        '--resume[Resume an interrupted run at the stage it stopped in]::run id:' \
        '--fresh[Skip the offer to resume an interrupted or cancelled run]' \
        '--yes[Skip confirmation prompts]' \
        '-y[Skip confirmation prompts]' \
        '--budget[Cost budget limit in USD]:amount:' \
        '--cost[Opt-in cost profile]:profile:(lean off)' \
        '--model[Model or route override]:model:' \
        '--max-cost[Spend cap in USD]:amount:' \
        '--no-pr[Build and verify without opening a pull request]' \
        '--explain-route[Print the route without running]' \
        '--max-iterations[Max iterations]:number:' \
        '--attempts[Independent attempts in worktrees, 1-5]:number:(1 2 3 4 5)' \
        '*:spec file:_loki_spec_files'
}

# Bias spec completion toward the file shapes Loki accepts (.md/.json/.txt/
# .yaml/.yml), while still offering directories so the user can navigate into a
# subfolder. Mirrors the bash completion. Makes the most-common command
# tab-driven and typo-proof, cutting "PRD file not found" mistakes.
function _loki_spec_files {
    _alternative \
        'specs:spec file:_files -g "*.(md|json|txt|yaml|yml)"' \
        'dirs:directory:_files -/'
}

function _loki_council {
    local -a council_cmds
    council_cmds=(
        'status:Council status'
        'verdicts:Show verdicts'
        'convergence:Check convergence'
        'force-review:Force a manual review'
        'report:Generate report'
        'config:Council configuration'
        'help:Council help'
    )
    _describe -t council_cmds 'council subcommand' council_cmds
}

function _loki_compound {
    local -a cmds
    cmds=(
        'list:List solutions by category'
        'show:Show solutions in a category'
        'search:Search across solutions'
        'run:Trigger compounding manually'
        'stats:Show solution statistics'
        'help:Compound help'
    )
    _describe -t cmds 'compound subcommand' cmds
}

function _loki_provider {
    local -a cmds
    cmds=(
        'show:Display current provider'
        'set:Set default provider'
        'list:List available providers (--json: name, tier, installed, version)'
        'info:Get provider information (--json: capability contract)'
        'matrix:Show the capability matrix'
        'help:Provider help'
    )
    _describe -t cmds 'provider subcommand' cmds
}

function _loki_plan {
    _arguments \
        '--json[Machine-readable JSON output]' \
        '--verbose[Detailed per-iteration breakdown]' \
        '--spec[Write editable acceptance criteria to .loki/specs/<slug>.md]' \
        '--fast[One-screen plan from the small tier, then a refine diff]' \
        '--requirements[Print the last run requirement-to-check map (read-only)]' \
        '*:prd file:_files'
}

function _loki_memory {
    local -a cmds
    cmds=(
        'list:List all learnings'
        'show:Display specific type'
        'search:Search learnings'
        'stats:Show statistics'
        'export:Export learnings'
        'clear:Clear learnings'
        'dedupe:Remove duplicates'
        'index:Memory index'
        'timeline:Memory timeline'
        'consolidate:Consolidate memory'
        'economics:Token economics'
        'retrieve:Retrieve relevant memory'
        'episode:Manage episodes'
        'pattern:Manage patterns'
        'skill:Manage skills'
        'vectors:Vector search'
        'lessons:List PR lessons (--json)'
        'learn:Learn from a merged PR'
        'promote:Share a PR lesson with every repo'
        'forget:Delete a PR lesson'
        'help:Memory help'
    )
    _describe -t cmds 'memory subcommand' cmds
}

function _loki_config {
    local -a cmds
    cmds=(
        'show:Display current config'
        'init:Initialize config file'
        'edit:Edit in default editor'
        'path:Show config file path'
        'help:Config help'
    )
    _describe -t cmds 'config subcommand' cmds
}

function _loki_dashboard {
    local -a cmds
    cmds=(
        'start:Start dashboard server'
        'stop:Stop dashboard server'
        'status:Get dashboard status'
        'url:Get dashboard URL'
        'open:Open dashboard in browser'
        'help:Dashboard help'
    )
    _describe -t cmds 'dashboard subcommand' cmds
}

function _loki_sandbox {
    local -a cmds
    cmds=(
        'start:Start sandbox container'
        'stop:Stop sandbox'
        'status:Check status'
        'logs:View logs'
        'shell:Open interactive shell'
        'build:Build sandbox image'
        'help:Sandbox help'
    )
    _describe -t cmds 'sandbox subcommand' cmds
}

function _loki_notify {
    local -a cmds
    cmds=(
        'test:Test all channels'
        'slack:Send to Slack'
        'discord:Send to Discord'
        'webhook:Send to webhook'
        'status:Show configuration'
        'help:Notify help'
    )
    _describe -t cmds 'notify subcommand' cmds
}

function _loki_enterprise {
    local -a cmds
    cmds=(
        'status:Show enterprise status'
        'token:Manage API tokens'
        'audit:Audit log commands'
        'help:Enterprise help'
    )
    _describe -t cmds 'enterprise subcommand' cmds
}

function _loki_projects {
    local -a cmds
    cmds=(
        'list:List registered projects'
        'show:Show project details'
        'register:Register new project'
        'add:Alias for register'
        'remove:Unregister a project'
        'discover:Auto-discover projects'
        'sync:Sync project data'
        'health:Check project health'
        'help:Projects help'
    )
    _describe -t cmds 'projects subcommand' cmds
}

function _loki_telemetry {
    local -a cmds
    cmds=(
        'status:Show telemetry config'
        'enable:Enable OTEL'
        'disable:Disable OTEL for current project'
        'stop:Permanently opt out across all sessions'
        'start:Remove persistent opt-out'
        'show:Show telemetry schema and last debug events'
        'help:Telemetry help'
    )
    _describe -t cmds 'telemetry subcommand' cmds
}

function _loki_agent {
    local -a cmds
    cmds=(
        'list:List agent types'
        'info:Show agent type details'
        'run:Run agent with prompt'
        'start:Start agent in background'
        'help:Agent help'
    )
    _describe -t cmds 'agent subcommand' cmds
}

function _loki_reset {
    local -a cmds
    cmds=(
        'all:Reset all state'
        'retries:Reset retry counter'
        'failed:Clear failed task queue'
        'help:Reset help'
    )
    _describe -t cmds 'reset subcommand' cmds
}

function _loki_issue {
    _arguments \
        '--repo[Specify repository]:repo:' \
        '--start[Start after generating PRD]' \
        '--dry-run[Preview without saving]' \
        '--output[Custom output path]:file:_files' \
        '1:subcommand:(parse view)'
}

function _loki_context {
    local -a cmds
    cmds=(
        'show:Show context window usage breakdown'
        'files:List files in context with token estimates'
        'tools:Show tool token usage per origin'
        'add:Add file to context'
        'clear:Clear accumulated context'
        'help:Context help'
    )
    _describe -t cmds 'context subcommand' cmds

    case $line[1] in
        add)
            _files
            ;;
    esac
}

function _loki_code {
    local -a cmds
    cmds=(
        'overview:Generate workspace overview'
        'symbols:Search for symbols'
        'deps:Show dependency graph'
        'hotspots:Find code hotspots'
        'diff:Show colored diff'
        'help:Code help'
    )
    _describe -t cmds 'code subcommand' cmds

    case $line[1] in
        overview)
            _arguments \
                '--silent[Compact output]' \
                '*:directory:_directories'
            ;;
        deps)
            _files
            ;;
        hotspots)
            _arguments \
                '--top[Number of results]:number:'
            ;;
        symbols)
            ;;
    esac
}

_loki "$@"
