"""Verbose help rendering for Hive trace CLI.

Phase-2 extraction slice: moved from `hiveos.observe` to reduce monolith size
without behavior changes.
"""

from hiveos_trace import terminal_style as _term


def _command_path_from_argv(raw_argv):
    tokens = [str(item) for item in (raw_argv or []) if str(item or "").strip()]
    non_flags = [token for token in tokens if not token.startswith("-")]
    if not non_flags:
        return tuple()
    first = non_flags[0]
    if first == "trace":
        if len(non_flags) >= 2:
            second = non_flags[1]
            if second in {"flow", "insight", "ops", "tei", "artifacts"} and len(non_flags) >= 3:
                return ("trace", second, non_flags[2])
            return ("trace", second)
        return ("trace",)
    return (first,)


def print_verbose_help(raw_argv):
    path = _command_path_from_argv(raw_argv)
    text_map = {
        tuple(): """Hive CLI (verbose)
Purpose:
  Local-first trace harness for wrapping commands, inspecting execution, and replaying behavior.
Core flow:
  1) hive trace run -- <command>
  2) hive trace ls
  3) hive trace summary <run_id>
  4) hive trace diagnose <run_id>
  5) hive trace replay <run_id> [--from-step-id | --from-checkpoint-id]
Tip:
  Use '--help' on any subcommand for complete flag details.
""",
        ("trace",): """hive trace (verbose)
Purpose:
  Command group for primitives, insight macros, and ops lifecycle controls.
Categories:
  primitives: run/ls/show/tail/summary/diff/diagnose/replay/replay-plan/checkpoint/anchors/flow/artifacts
  insight:    insight explain|drift|health
  ops:        ops archive|unarchive|prune|reconcile|export|import
Common commands:
  hive trace run -- <command>
  hive trace ls --limit 20
  hive trace show <run_id>
  hive trace replay-plan <run_id> --from-step-id <id>
  hive trace ops reconcile --stale-after 10m
""",
        ("trace", "run"): """hive trace run (verbose)
Purpose:
  Execute a command with trace capture while preserving original exit behavior.
Examples:
  hive trace run -- python agent.py
  hive trace run --name smoke --timeout-sec 60 --open -- python -m unittest -q
Notes:
  - '--' separates hive flags from wrapped command argv.
  - '--proxy' enables OpenAI-compatible proxy capture.
""",
        ("quickstart",): """hive quickstart (verbose)
Purpose:
  Run a fast local smoke flow to verify trace capture and next-step commands.
Examples:
  hive quickstart --no-open
  hive quickstart --open --ui-url http://localhost:5173
""",
        ("doctor",): """hive doctor (verbose)
Purpose:
  Validate local runtime readiness for hive trace.
Checks:
  - python runtime version
  - trace home writable
  - optional UI reachability
Examples:
  hive doctor
  hive doctor --ui-url http://localhost:5173
""",
        ("trace", "replay"): """hive trace replay (verbose)
Purpose:
  Re-run a prior captured command with optional anchor constraints.
Examples:
  hive trace replay observe-run:abc123
  hive trace replay observe-run:abc123 --from-step-id step_7
  hive trace replay observe-run:abc123 --from-checkpoint-id ckpt_2 --no-open
Notes:
  - '--from-step-id' and '--from-checkpoint-id' are mutually exclusive.
  - Replay lineage fields are persisted on the new run.
""",
        ("trace", "replay-plan"): """hive trace replay-plan (verbose)
Purpose:
  Preview replay intent and anchor validation without executing by default.
Examples:
  hive trace replay-plan observe-run:abc123
  hive trace replay-plan observe-run:abc123 --from-step-id step_7
  hive trace replay-plan observe-run:abc123 --recommended --json
  hive trace replay-plan observe-run:abc123 --recommended --explain
  hive trace replay-plan observe-run:abc123 --from-step-id step_7 --emit-artifact --json
  hive trace replay-plan observe-run:abc123 --from-checkpoint-id ckpt_2 --apply
Notes:
  - '--apply' executes replay using the validated plan.
  - '--apply' and '--json' are mutually exclusive.
  - '--recommended' auto-selects highest-ranked admissible anchor when explicit anchor flags are omitted.
  - '--explain' prints selected/rejected candidate rationale in text mode.
  - '--emit-artifact' writes replay-plan payload to JSON for downstream tooling.
  - Use anchors command first when IDs are unknown: hive trace anchors <run_id>
""",
        ("trace", "anchors"): """hive trace anchors (verbose)
Purpose:
  Discover available step/checkpoint anchor IDs for a run.
Examples:
  hive trace anchors observe-run:abc123
  hive trace anchors observe-run:abc123 --json
""",
        ("trace", "checkpoint"): """hive trace checkpoint (verbose)
Purpose:
  Emit a checkpoint marker on an existing run for replay/debugger workflows.
Examples:
  hive trace checkpoint observe-run:abc123 ckpt:step42
  hive trace checkpoint observe-run:abc123 ckpt:step42 --step-name tool.result --state-ref state://tool/42 --json
""",
        ("trace", "ls"): """hive trace ls (verbose)
Purpose:
  List recent traced runs with lifecycle and live-state context.
Examples:
  hive trace ls
  hive trace ls --limit 20 --status running
  hive trace ls --json
""",
        ("trace", "show"): """hive trace show (verbose)
Purpose:
  Show detailed event documents for one run.
Examples:
  hive trace show observe-run:abc123
  hive trace show observe-run:abc123 --limit 300 --json
""",
        ("trace", "tail"): """hive trace tail (verbose)
Purpose:
  Tail recent events globally or for one run, with optional follow mode.
Examples:
  hive trace tail --limit 80
  hive trace tail --run-id observe-run:abc123 --follow
  hive trace tail --run-id observe-run:abc123 --json
""",
        ("trace", "artifacts"): """hive trace artifacts (verbose)
Purpose:
  Inspect persisted trace artifacts (starting with replay-plan manifests).
Examples:
  hive trace artifacts ls --type replay_plan --json
  hive trace artifacts show replay-plan:abc123
  hive trace artifacts show .\\path\\to\\artifact.json --json
  hive trace artifacts replay replay-plan:abc123 --no-open
""",
        ("trace", "summary"): """hive trace summary (verbose)
Purpose:
  Print compact run summary including status, timing, output tails, and suggestions.
Examples:
  hive trace summary observe-run:abc123
  hive trace summary observe-run:abc123 --tail-lines 40 --json
""",
        ("trace", "diff"): """hive trace diff (verbose)
Purpose:
  Compare two runs and surface divergence in config, event stream, and output tails.
Examples:
  hive trace diff observe-run:a observe-run:b
  hive trace diff observe-run:a observe-run:b --json
""",
        ("trace", "diagnose"): """hive trace diagnose (verbose)
Purpose:
  Classify run outcomes and print actionable next-step recommendations.
Examples:
  hive trace diagnose observe-run:abc123
  hive trace diagnose observe-run:abc123 --json
""",
        ("trace", "open"): """hive trace open (verbose)
Purpose:
  Open a run in configured UI or fallback local status page.
Examples:
  hive trace open observe-run:abc123
  hive trace open observe-run:abc123 --ui-url http://localhost:5173
""",
        ("trace", "flow"): """hive trace flow (verbose)
Purpose:
  Inspect flow-level lineage assembled from step identifiers.
Examples:
  hive trace flow ls
  hive trace flow show <flow_id>
  hive trace flow diff <flow_a> <flow_b>
""",
        ("trace", "flow", "ls"): """hive trace flow ls (verbose)
Purpose:
  List recent flows with aggregate status and retry signals.
Examples:
  hive trace flow ls
  hive trace flow ls --limit 20 --json
""",
        ("trace", "flow", "show"): """hive trace flow show (verbose)
Purpose:
  Show timeline view for one flow_id.
Examples:
  hive trace flow show flow:abc123
  hive trace flow show flow:abc123 --event-limit 3000 --json
""",
        ("trace", "flow", "steps"): """hive trace flow steps (verbose)
Purpose:
  Show derived step summary for one flow_id.
Examples:
  hive trace flow steps flow:abc123
  hive trace flow steps flow:abc123 --json
""",
        ("trace", "flow", "diff"): """hive trace flow diff (verbose)
Purpose:
  Compare two flows and highlight divergence and retry deltas.
Examples:
  hive trace flow diff flow:a flow:b
  hive trace flow diff flow:a flow:b --json
""",
        ("trace", "tei"): """hive trace tei (verbose)
Purpose:
  TEI namespace for contract validation and ingest into trace store.
Examples:
  hive trace tei validate --file .\\event.json
  hive trace tei ingest --file .\\events.json
""",
        ("trace", "tei", "validate"): """hive trace tei validate (verbose)
Purpose:
  Validate one TEI event object or TEI batch array.
Examples:
  hive trace tei validate --file .\\event.json
  type .\\event.json | hive trace tei validate
  hive trace tei validate --file .\\events.json --json
""",
        ("trace", "tei", "ingest"): """hive trace tei ingest (verbose)
Purpose:
  Validate and ingest TEI object/array into local trace store.
Examples:
  hive trace tei ingest --file .\\event.json
  hive trace tei ingest --file .\\events.json --agent-id observer.tei
  hive trace tei ingest --file .\\events.json --json
""",
        ("trace", "artifacts", "ls"): """hive trace artifacts ls (verbose)
Purpose:
  List persisted trace artifacts.
Examples:
  hive trace artifacts ls
  hive trace artifacts ls --type replay_plan --json
""",
        ("trace", "artifacts", "show"): """hive trace artifacts show (verbose)
Purpose:
  Show one artifact by id or file path.
Examples:
  hive trace artifacts show replay-plan:abc123
  hive trace artifacts show .\\artifact.json --json
""",
        ("trace", "artifacts", "replay"): """hive trace artifacts replay (verbose)
Purpose:
  Execute replay from a persisted replay-plan artifact.
Examples:
  hive trace artifacts replay replay-plan:abc123 --no-open
  hive trace artifacts replay .\\artifact.json --name replay:manual
""",
        ("trace", "insight"): """hive trace insight (verbose)
Purpose:
  Macro layer that composes primitives into concise answers with provenance.
Examples:
  hive trace insight explain <run_id>
  hive trace insight drift <run_a> <run_b>
  hive trace insight health --window 24h
Notes:
  - Insight macros do not replace primitives.
  - Use '--emit-primitive' to print equivalent primitive commands.
""",
        ("trace", "insight", "explain"): """hive trace insight explain (verbose)
Purpose:
  Explain one run via answer/evidence/actions generated from primitives.
Examples:
  hive trace insight explain observe-run:abc123
  hive trace insight explain observe-run:abc123 --show-source --json
""",
        ("trace", "insight", "drift"): """hive trace insight drift (verbose)
Purpose:
  Explain how two runs diverged and what to inspect next.
Examples:
  hive trace insight drift observe-run:a observe-run:b
  hive trace insight drift observe-run:a observe-run:b --emit-primitive
""",
        ("trace", "insight", "health"): """hive trace insight health (verbose)
Purpose:
  Report aggregate run health for a rolling time window.
Examples:
  hive trace insight health --window 24h
  hive trace insight health --window 7d --show-source --json
""",
        ("trace", "ops"): """hive trace ops (verbose)
Purpose:
  Lifecycle and admin controls for trace hygiene and portability.
Examples:
  hive trace ops archive <run_id>
  hive trace ops prune --older-than 30d
  hive trace ops reconcile --stale-after 5m
""",
        ("trace", "ops", "archive"): """hive trace ops archive (verbose)
Purpose:
  Archive one run from active listings.
Examples:
  hive trace ops archive observe-run:abc123
  hive trace ops archive observe-run:abc123 --reason cleanup --actor operator
""",
        ("trace", "ops", "unarchive"): """hive trace ops unarchive (verbose)
Purpose:
  Restore an archived run to active listings.
Examples:
  hive trace ops unarchive observe-run:abc123
""",
        ("trace", "ops", "prune"): """hive trace ops prune (verbose)
Purpose:
  Prune older run records and optional trace events.
Examples:
  hive trace ops prune --older-than 30d
  hive trace ops prune --older-than 7d --include-active --drop-events
""",
        ("trace", "ops", "reconcile"): """hive trace ops reconcile (verbose)
Purpose:
  Reconcile stale running runs into terminal statuses.
Examples:
  hive trace ops reconcile
  hive trace ops reconcile --stale-after 10m --json
""",
        ("trace", "ops", "export"): """hive trace ops export (verbose)
Purpose:
  Export run record + events as a portable bundle.
Examples:
  hive trace ops export observe-run:abc123 --bundle .\\run.bundle.json
""",
        ("trace", "ops", "import"): """hive trace ops import (verbose)
Purpose:
  Import a run bundle into local storage.
Examples:
  hive trace ops import --bundle .\\run.bundle.json
  hive trace ops import --bundle .\\run.bundle.json --as-run-id observe-run:shared-001
""",
    }
    message = text_map.get(path)
    if message is None and len(path) >= 2 and path[:2] == ("trace", "flow"):
        message = text_map.get(("trace", "flow", path[2])) or text_map[("trace", "flow")]
    if message is None and len(path) >= 2 and path[:2] == ("trace", "tei"):
        message = text_map.get(("trace", "tei", path[2])) or text_map[("trace", "tei")]
    if message is None and len(path) >= 2 and path[:2] == ("trace", "artifacts"):
        message = text_map.get(("trace", "artifacts", path[2])) or text_map[("trace", "artifacts")]
    if message is None and len(path) >= 2 and path[:2] == ("trace", "insight"):
        message = text_map.get(("trace", "insight", path[2])) or text_map[("trace", "insight")]
    if message is None and len(path) >= 2 and path[:2] == ("trace", "ops"):
        message = text_map.get(("trace", "ops", path[2])) or text_map[("trace", "ops")]
    if message is None:
        message = "Verbose help is not defined for this command path yet. Use '--help' for full option details."
    text = message.rstrip() + "\n"
    print(_term.style_help_text(text).rstrip())
    print("")
    return 0

