#!/usr/bin/env bash
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./resolve-odb-cli.sh
source "$script_dir/resolve-odb-cli.sh"

render_cli_prefix() {
  local rendered=()
  local part
  for part in "${ODB_CLI[@]}"; do
    rendered+=("$(printf '%q' "$part")")
  done
  printf '%s' "${rendered[*]}"
}

CLI_PREFIX="$(render_cli_prefix)"
PACKAGE_ROOT="$(cd "$script_dir/../../.." && pwd)"
TRANSCRIPT_PROBE_PATH="$(printf '%q' "$PACKAGE_ROOT/scripts/youtube-transcript-live-probe.mjs")"

print_daemon_preflight() {
  cat <<EOF
# Daemon preflight for daemon-backed workflows:
$CLI_PREFIX status --daemon --output-format json
# Continue only when data.fingerprintCurrent === true.
EOF
}

print_extension_readiness() {
  cat <<EOF
# Extension readiness preflight:
$CLI_PREFIX status --daemon --output-format json
# Continue only when data.fingerprintCurrent === true, data.relay.extensionConnected === true, and data.relay.extensionHandshakeComplete === true.
# Treat data.relay.opsConnected, data.relay.canvasConnected, and data.relay.cdpConnected as diagnostic or lane-specific presence fields.
EOF
}

print_managed_profile_readiness() {
  cat <<EOF
# Managed headed profile preflight:
$CLI_PREFIX status --daemon --output-format json
# Continue only when data.fingerprintCurrent === true. Use a dedicated non-default --profile for non-Google login continuity.
# Use extension /ops instead when you need live active-tab reuse or user-owned Google OAuth continuity.
EOF
}

print_pinterest_multi_pin_harvest_guidance() {
  cat <<EOF
# Multi-pin Pinterest harvest agent pattern. This is guidance over inspiredesign harvest, not a standalone product workflow.
# 1. Run the query discovery command above with --query and --provider social/pinterest.
# 2. Read meta.discovery.acceptedUrls from the JSON output or artifact metadata.
# 3. Keep only canonical https://www.pinterest.com/pin/<id>/ URLs.
# 4. Run one canonical harvest per selected pin in a dedicated managed headed profile and omit --output-dir:
$CLI_PREFIX inspiredesign harvest --brief "Premium digital photography studio landing page" --provider social/pinterest --url "https://www.pinterest.com/pin/<pin-id>/" --max-references 1 --visual-evidence required --browser-mode managed --profile pinterest-design --use-cookies --cookie-policy required --challenge-automation-mode browser_with_helper --mode json --output-format json
# 5. Each omitted run returns its own artifact_path under .opendevbrowser/inspiredesign/<runId>; inspect that path instead of creating a custom workflow root.
# 6. Canonical harvest opens the exact canonical pin in the active managed or extension workflow session before byte-backed pin-media extraction. Switch to extension /ops only for live-tab reuse or user-owned Google continuity.
# 7. Trust only outputs with top-level ready=true, productSuccess=true, artifactAuthority=product_ready, evidenceAuthority=pin_media_ready, non-empty ranked-references.json, and manifest-backed pin-media-index.json. snapshot_ready or motion_ready are not substitutes for pin-media readiness.
# 8. Use media-analysis.json for deterministic design facts from trusted saved pin media only. It is not readiness authority, and pin-media-index.json remains the only pin-media readiness authority.
# 9. Do not claim readable text extraction, exact copy, font families, OCR, model vision, Tesseract, OpenCV, Sharp, browser canvas analysis, new dependencies, or raw mediaAnalysis in canvas-plan.request.json.
EOF
}

print_help() {
  cat <<'EOF'
OpenDevBrowser workflow router

Usage:
  ./skills/opendevbrowser-best-practices/scripts/odb-workflow.sh <workflow>

Workflows:
  provider-search
  provider-crawl
  inspiredesign
  parallel-multipage-safe
  qa-debug
  social-readonly-check
  canvas-preflight
  canvas-feedback-eval
  parity-check
  release-direct-gates
  skill-runtime-audit
  validated-capabilities
  surface-audit
  ops-channel-check
  cdp-channel-check
  mode-flag-matrix
  robustness-audit
  list
EOF
}

workflow="${1:-list}"

case "$workflow" in
  list)
    print_help
    ;;
  provider-search)
    cat <<'EOF'
opendevbrowser_launch noExtension=true
opendevbrowser_goto sessionId="<session-id>" url="<provider-search-url>"
opendevbrowser_wait sessionId="<session-id>" until="networkidle"
opendevbrowser_snapshot sessionId="<session-id>" format="actionables"
opendevbrowser_network_poll sessionId="<session-id>" max=50
EOF
    ;;
  provider-crawl)
    cat <<'EOF'
opendevbrowser_launch noExtension=true
opendevbrowser_goto sessionId="<session-id>" url="<seed-url>"
opendevbrowser_wait sessionId="<session-id>" until="networkidle"
opendevbrowser_snapshot sessionId="<session-id>" format="actionables"
opendevbrowser_scroll sessionId="<session-id>" dy=1000
opendevbrowser_wait sessionId="<session-id>" until="networkidle"
EOF
    ;;
  inspiredesign)
    print_daemon_preflight
    cat <<EOF
# Pair with opendevbrowser-design-agent when the contract will flow into implementation or /canvas work.
# Routine workflow runs should omit --output-dir and inspect the returned artifact_path first.
# When --output-dir is omitted, persisted bundles use .opendevbrowser/<namespace>/<runId>; use --output-dir .opendevbrowser only when a wrapper requires an explicit workflow root.
# URL-backed inspiredesign run forces deep capture for DOM/layout diagnostics; do not disable capture for URL-backed runs.
$CLI_PREFIX inspiredesign run --brief "Design a premium docs workspace" --url "https://example.com/reference-a" --url "https://example.com/reference-b" --include-prototype-guidance --mode json --output-format json
EOF
    print_managed_profile_readiness
    cat <<EOF
$CLI_PREFIX inspiredesign harvest --brief "Premium digital photography studio landing page" --query "Pinterest premium digital photography studio landing page cinematic parallax portfolio" --provider social/pinterest --max-references 5 --visual-evidence required --browser-mode managed --profile pinterest-design --use-cookies --cookie-policy required --challenge-automation-mode browser_with_helper --mode json --output-format json
# Inspect top-level ready, productSuccess, artifactAuthority, evidenceAuthority, nextStepGuidance.readiness, and doNotProceedIf before Canvas continuation. For non-product-ready evidence, follow recovery-first guidance.
# Review visual-evidence.json, screenshot-index.json, motion-evidence.json, pin-media-evidence.json, pin-media-index.json, media-analysis.json, ranked-references.json, and meta-prompt.md before design or Canvas work.
EOF
    print_pinterest_multi_pin_harvest_guidance
    ;;
  parallel-multipage-safe)
    cat <<'EOF'
# Reliable parallel pattern (as-is):
# - Worker A owns session-a
# - Worker B owns session-b
# - Keep each session serial (snapshot -> action -> snapshot)
# - Do NOT interleave independent target-use streams in one session
# - Managed + persisted profiles: use unique profile paths per session

opendevbrowser_launch noExtension=true
opendevbrowser_launch noExtension=true

# Worker A loop
opendevbrowser_goto sessionId="<session-a>" url="<url-a1>"
opendevbrowser_wait sessionId="<session-a>" until="networkidle"
opendevbrowser_snapshot sessionId="<session-a>" format="actionables"

# Worker B loop
opendevbrowser_goto sessionId="<session-b>" url="<url-b1>"
opendevbrowser_wait sessionId="<session-b>" until="networkidle"
opendevbrowser_snapshot sessionId="<session-b>" format="actionables"
EOF
    ;;
  qa-debug)
    cat <<'EOF'
opendevbrowser_snapshot sessionId="<session-id>" format="outline"
opendevbrowser_console_poll sessionId="<session-id>" max=100
opendevbrowser_network_poll sessionId="<session-id>" max=100
opendevbrowser_screenshot sessionId="<session-id>"
EOF
    ;;
  social-readonly-check)
    cat <<'EOF'
# Read-only social validation (default, no posting).
opendevbrowser_snapshot sessionId="<session-id>" format="actionables"
opendevbrowser_debug_trace_snapshot sessionId="<session-id>" maxEvents=50
opendevbrowser_network_poll sessionId="<session-id>" max=100
EOF
    ;;
  canvas-preflight)
    print_daemon_preflight
    cat <<EOF
cat skills/opendevbrowser-best-practices/assets/templates/canvas-handshake-example.json
cat skills/opendevbrowser-best-practices/assets/templates/canvas-generation-plan.v1.json
$CLI_PREFIX canvas --command canvas.session.open --params '{"requestId":"req_open_01","browserSessionId":"<browser-session-id>","documentId":null,"repoPath":null,"mode":"dual-track"}' --output-format json
# Read handshake before any mutation. Inspect planStatus, preflightState, generationPlanRequirements.allowedValues, generationPlanIssues, and guidance.recommendedNextCommands.
$CLI_PREFIX canvas --command canvas.plan.set --params-file skills/opendevbrowser-best-practices/assets/templates/canvas-generation-plan.v1.json --output-format json
# Replace placeholders in the plan file with canvasSessionId, leaseId, and documentId from the open response.
# If canvas.plan.set succeeds with planStatus=accepted or preflightState=plan_accepted, follow the returned guidance into canvas.document.patch.
# If canvas.plan.set returns generation_plan_invalid, read guidance.nextStepGuidance, guidance.paramsExamples, guidance.fieldExamples, guidance.validationChecks, and guidance.doNotProceedIf, then repair the params file and retry.
# Optional diagnostics after generation_plan_invalid:
# $CLI_PREFIX canvas --command canvas.plan.get --params '{"requestId":"req_plan_get_01","canvasSessionId":"<canvas-session-id>","leaseId":"<lease-id>","documentId":"<document-id>"}' --output-format json
# or re-read with canvas.capabilities.get to inspect generationPlanIssues before resubmitting canvas.plan.set.
EOF
    ;;
  canvas-feedback-eval)
    print_daemon_preflight
    cat <<EOF
cat skills/opendevbrowser-best-practices/artifacts/canvas-governance-playbook.md
cat skills/opendevbrowser-best-practices/assets/templates/canvas-feedback-eval.json
cat skills/opendevbrowser-best-practices/assets/templates/canvas-blocker-checklist.json
$CLI_PREFIX canvas --command canvas.feedback.poll --params '{"requestId":"req_feedback_01","canvasSessionId":"<canvas-session-id>","documentId":"<document-id>","targetId":"<target-id>","afterCursor":null}' --output-format json
# Verify every feedback item is target-attributed and uses approved categories. If feedback returns preflight-blocker, return to canvas.plan.set first.
$CLI_PREFIX canvas --command canvas.preview.refresh --params '{"requestId":"req_refresh_01","canvasSessionId":"<canvas-session-id>","leaseId":"<lease-id>","targetId":"<target-id>","refreshMode":"full"}' --output-format json
$CLI_PREFIX canvas --command canvas.document.save --params '{"requestId":"req_save_01","canvasSessionId":"<canvas-session-id>","leaseId":"<lease-id>","documentId":"<document-id>","repoPath":null}' --output-format json
# Save should fail or warn when requiredBeforeSave governance blocks remain unresolved.
EOF
    ;;
  parity-check)
    cat <<'EOF'
npm run test -- tests/parity-matrix.test.ts
npm run test -- tests/tools.test.ts tests/daemon-commands.integration.test.ts
./skills/opendevbrowser-best-practices/scripts/validate-skill-assets.sh
EOF
    ;;
  release-direct-gates)
    print_daemon_preflight
    cat <<'EOF'
# artifacts/release/vX.Y.Z paths are local-only release proof outputs.
# Normal omitted workflow outputs should be discovered from returned artifact_path first; persisted bundles use .opendevbrowser/<namespace>/<runId>.
mkdir -p artifacts/release/vX.Y.Z
node scripts/provider-direct-runs.mjs --release-gate --out artifacts/release/vX.Y.Z/provider-direct-runs.json
node scripts/live-regression-direct.mjs --release-gate --out artifacts/release/vX.Y.Z/live-regression-direct.json
EOF
    ;;
  skill-runtime-audit)
    print_daemon_preflight
    cat <<'EOF'
npm run build
node scripts/docs-drift-check.mjs
# Discovery, lifecycle, and help parity
npm run test -- tests/skill-loader.test.ts tests/skill-list-tool.test.ts tests/cli-skills-installer.test.ts
npm run test -- tests/cli-help.test.ts tests/cli-help-parity.test.ts tests/skill-runtime-audit.test.ts tests/skill-workflow-packs.test.ts
npx opendevbrowser --help
npx opendevbrowser help
WORKDIR=$(mktemp -d /tmp/odb-skill-audit-XXXXXX)
OPENCODE_CONFIG_DIR="$WORKDIR/config" CODEX_HOME="$WORKDIR/codex-home" CLAUDECODE_HOME="$WORKDIR/claude-home" AMP_CLI_HOME="$WORKDIR/amp-home" npx opendevbrowser --global --full --no-prompt
OPENCODE_CONFIG_DIR="$WORKDIR/config" CODEX_HOME="$WORKDIR/codex-home" CLAUDECODE_HOME="$WORKDIR/claude-home" AMP_CLI_HOME="$WORKDIR/amp-home" npx opendevbrowser --uninstall --global --no-prompt
./skills/opendevbrowser-best-practices/scripts/validate-skill-assets.sh
./skills/opendevbrowser-best-practices/scripts/run-robustness-audit.sh
./skills/opendevbrowser-continuity-ledger/scripts/validate-skill-assets.sh
./skills/opendevbrowser-data-extraction/scripts/validate-skill-assets.sh
./skills/opendevbrowser-design-agent/scripts/validate-skill-assets.sh
./skills/opendevbrowser-motion-design/scripts/validate-skill-assets.sh
./skills/opendevbrowser-form-testing/scripts/validate-skill-assets.sh
./skills/opendevbrowser-login-automation/scripts/validate-skill-assets.sh
./skills/opendevbrowser-product-presentation-asset/scripts/validate-skill-assets.sh
./skills/opendevbrowser-research/scripts/validate-skill-assets.sh
./skills/opendevbrowser-shopping/scripts/validate-skill-assets.sh
# Explicit artifacts/skill-runtime-audit outputs are local-only audit proof.
# Omitted provider workflow outputs should be discovered from returned artifact_path first; persisted bundles use .opendevbrowser/<namespace>/<runId>.
node scripts/skill-runtime-audit.mjs --smoke --out artifacts/skill-runtime-audit/smoke.json
node scripts/skill-runtime-audit.mjs --out artifacts/skill-runtime-audit/full.json
EOF
    ;;
  validated-capabilities)
    print_daemon_preflight
    cat <<EOF
# Public-first YouTube transcript probe
node $TRANSCRIPT_PROBE_PATH --url "https://www.youtube.com/watch?v=aircAruvnKk" --youtube-mode auto --out artifacts/capability-fix/youtube-transcript-auto.json

# Routine workflow runs should omit --output-dir and inspect the returned artifact_path first.
# When --output-dir is omitted, persisted bundles use .opendevbrowser/<namespace>/<runId>; use --output-dir .opendevbrowser only when a wrapper requires an explicit workflow root.

# Evidence-gated research primitive with explicit public source families
# Load opendevbrowser-research first, then inspect records.json, context.json, meta.json, and report.md before publishing claims.
$CLI_PREFIX research run --topic "Chrome extension debugging workflows" --days 30 --sources web,community --mode json --output-format json

# Deterministic shopping reruns with explicit providers
$CLI_PREFIX shopping run --query "wireless ergonomic mouse" --providers shopping/bestbuy,shopping/ebay --budget 150 --browser-mode managed --use-cookies --challenge-automation-mode browser_with_helper --mode json --output-format json
$CLI_PREFIX shopping run --query "27 inch 4k monitor" --providers shopping/bestbuy,shopping/ebay --budget 350 --sort lowest_price --browser-mode managed --use-cookies --challenge-automation-mode browser_with_helper --mode json --output-format json

# Public-reference inspiredesign contract synthesis
$CLI_PREFIX inspiredesign run --brief "Design a premium docs workspace" --url "https://example.com/reference-a" --url "https://example.com/reference-b" --include-prototype-guidance --mode json --output-format json
EOF
    print_managed_profile_readiness
    cat <<EOF
# Browser-native Pinterest recipe. Continue only when top-level ready=true, productSuccess=true, artifactAuthority=product_ready, evidenceAuthority=pin_media_ready, ranked references are non-empty, and pin-media-index.json is manifest-backed.
$CLI_PREFIX inspiredesign harvest --brief "Premium digital photography studio landing page" --query "Pinterest premium digital photography studio landing page cinematic parallax portfolio" --provider social/pinterest --max-references 5 --visual-evidence required --browser-mode managed --profile pinterest-design --use-cookies --cookie-policy required --challenge-automation-mode browser_with_helper --mode json --output-format json
EOF
    print_pinterest_multi_pin_harvest_guidance
    cat <<EOF

# Region note: advisory unless output reports meta.selection.region_authoritative=true
$CLI_PREFIX shopping run --query "wireless earbuds" --providers shopping/amazon --region us --browser-mode managed --use-cookies --challenge-automation-mode browser_with_helper --mode json --output-format json
EOF
    ;;
  surface-audit)
    cat <<'EOF'
cat docs/SURFACE_REFERENCE.md
cat skills/opendevbrowser-best-practices/artifacts/command-channel-reference.md
cat skills/opendevbrowser-best-practices/assets/templates/surface-audit-checklist.json
./skills/opendevbrowser-best-practices/scripts/validate-skill-assets.sh
EOF
    ;;
  ops-channel-check)
    cat <<EOF
$CLI_PREFIX serve
EOF
    print_daemon_preflight
    cat <<EOF
$CLI_PREFIX launch --extension-only --wait-for-extension --output-format json
$CLI_PREFIX status --daemon --output-format json
# Verify data.fingerprintCurrent=true, data.relay.extensionConnected=true, and data.relay.extensionHandshakeComplete=true after launch. Treat data.relay.opsConnected as diagnostic presence only.
cat skills/opendevbrowser-best-practices/assets/templates/ops-request-envelope.json
EOF
    ;;
  cdp-channel-check)
    cat <<EOF
$CLI_PREFIX serve
EOF
    print_daemon_preflight
    cat <<EOF
$CLI_PREFIX launch --extension-only --extension-legacy --wait-for-extension --output-format json
$CLI_PREFIX status --daemon --output-format json
# Verify data.fingerprintCurrent=true, data.relay.extensionConnected=true, and data.relay.extensionHandshakeComplete=true after launch. data.relay.cdpConnected is active-legacy-session-only and true only while the legacy /cdp session is active.
cat skills/opendevbrowser-best-practices/assets/templates/cdp-forward-envelope.json
EOF
    ;;
  mode-flag-matrix)
    print_daemon_preflight
    cat <<EOF
cat skills/opendevbrowser-best-practices/assets/templates/mode-flag-matrix.json
$CLI_PREFIX launch --no-extension --output-format json
$CLI_PREFIX launch --extension-only --wait-for-extension --output-format json
$CLI_PREFIX launch --extension-only --extension-legacy --wait-for-extension --output-format json
EOF
    ;;
  robustness-audit)
    cat <<'EOF'
cat skills/opendevbrowser-best-practices/artifacts/browser-agent-known-issues-matrix.md
cat skills/opendevbrowser-best-practices/assets/templates/robustness-checklist.json
./skills/opendevbrowser-best-practices/scripts/run-robustness-audit.sh
EOF
    ;;
  *)
    echo "Unknown workflow: $workflow" >&2
    print_help
    exit 2
    ;;
esac
