#!/usr/bin/env bash
# Regenerate ALL reporting docs screenshots at 2560x1440 (1440P / QHD).
# Reuses cached dev auth (run an auth-refresh shot first). Each entry:
#   <out-relative-to-DOCS>|<app-path>|<extra shot.js flags>
set -u
set -f   # no glob: selectors contain [ ] brackets
cd "$(dirname "$0")" || exit 1
# Creds: single source of truth is evolution/.env (evoClaudeUser / evoClaudePasswd).
# Don't duplicate them here or in browser-tools/.env — derive at runtime.
EVO_ENV="/config/workspace/evolution/.env"
EVO_DEV_USER="$(sed -nE 's/.*evoClaudeUser"[[:space:]]*,[[:space:]]*"([^"]+)".*/\1/p' "$EVO_ENV")"
EVO_DEV_PASS="$(sed -nE 's/.*evoClaudePasswd"[[:space:]]*,[[:space:]]*"([^"]+)".*/\1/p' "$EVO_ENV")"
if [ -z "$EVO_DEV_USER" ] || [ -z "$EVO_DEV_PASS" ]; then
  echo "ERROR: could not read evoClaudeUser/evoClaudePasswd from $EVO_ENV" >&2; exit 1
fi
export EVO_DEV_USER EVO_DEV_PASS
DOCS="/config/workspace/evolution/docs/reporting/images"
WH="--width 2560 --height 1440"
R="index.php?page=report&file="
DASH="index.php?page=reportsdashboard"

ENTRIES=(
# --- overview ---
"overview/reports-dashboard.png|${DASH}|--full"
"overview/dashboard-search.png|${DASH}|--eval (function(){var s=document.getElementById('rdSearch');s.value='aged';s.dispatchEvent(new Event('input',{bubbles:true}));})() --wait 800"
# --- financials ---
"financials/aged-receivables.png|${R}arAged|"
"financials/aged-payables.png|${R}apAged|"
"financials/misaligned-invoices.png|${R}invoicesMisaligned|"
"financials/profit-and-loss.png|${R}finPL|--fill #plDate1::2023-07-01 --fill #plDate2::2024-06-30 --click #plRun --wait 1800"
"financials/revenue-by-month.png|${R}finRevenue|--select #revFy::2023 --click #revRun --wait 1800"
"financials/gst-bas-summary.png|${R}finGst|--select #gstFy::2023 --click #gstRun --wait 1800"
"financials/financials-cards.png|${DASH}|--selector .rd-cat-section[data-cat=\"financials\"]"
# --- sales ---
"sales/quote-performance-by-rep.png|${R}salesByRep|--select #qbrYear::2023-07-01 --click #qbrRun --wait 1800"
"sales/converted-quotes-by-client.png|${R}salesByRepCustomers|--select #qbrYear::2023-07-01 --click #qbrRun --wait 1800"
"sales/invoicing-advanced.png|${R}invoicesFiltered|--fill #datestart::2023-07-01 --eval filterReport() --wait 1800"
"sales/monthly-invoicing-by-client.png|${R}invoicesByRep|--select #ibrYear::2023-07-01 --click #ibrRun --wait 1800"
"sales/monthly-invoicing-by-rep.png|${R}invoicesByRepSummary|--select #ibrYear::2023-07-01 --click #ibrRun --wait 1800"
"sales/sales-cards.png|${DASH}|--selector .rd-cat-section[data-cat=\"sales\"]"
# --- purchasing ---
"purchasing/supplier-spend.png|${R}purSupplierSpend|--eval (function(){document.getElementById('spsTemplate').value='';document.getElementById('spsFrom').value='2023-07-01';document.getElementById('spsTo').value='2024-06-30';runSupplierSpend();})() --wait 1800"
"purchasing/open-po-commitments.png|${R}purOpenCommit|"
"purchasing/purchasing-by-job.png|${R}purByJob|"
# Purchase History defaults to the last 12 months and an empty result; drive it to the
# 36-month item x supplier roll-up so the price-movement columns have something in them.
"purchasing/purchase-history.png|${R}purHistory|--eval (function(){document.getElementById('phView').value='itemsupplier';phApplyTemplate('last_36');runPurchaseHistory();})() --wait 9000"
# --- projects ---
"projects/wip-summary.png|${R}projectWipSummary|"
"projects/closed-job-variation.png|${R}projectClosedVariation|"
"projects/project-billable-items.png|${R}projectBillableItems&id=5344|"
# --- timesheets (all populated by default) ---
"timesheets/monthly-billing.png|${R}timesheetMonthlyBilling|"
"timesheets/unbilled-wip-ageing.png|${R}tsUnbilledWipAgeing|"
"timesheets/project-labour-margin.png|${R}tsProjectLabourMargin|"
"timesheets/effective-bill-rate.png|${R}tsEffectiveBillRate|"
"timesheets/project-run-rate.png|${R}tsProjectRunRate|"
"timesheets/employee-utilization.png|${R}tsEmployeeUtilization|"
"timesheets/billable-mix.png|${R}tsBillableMix|"
"timesheets/outstanding-approvals.png|${R}tsApprovalsAgeing|"
"timesheets/missing-timesheets.png|${R}tsMissingTimesheets|"
# --- inventory ---
"inventory/inventory-list.png|${R}invnontracked|"
"inventory/stock-on-hand.png|${R}invSoh|"
"inventory/demand-deficit.png|${R}invDemandFinishGoods|"
"inventory/min-max-reorder.png|${R}invreorder|"
"inventory/reorder-insights.png|${R}invReorderInsights|"
"inventory/po-outstanding.png|${R}purOutstandingItems|"
"inventory/bom-restocking.png|${R}invBomRestock&branch=1|"
"inventory/bom-detail.png|${R}invbomrep|--eval (function(){runBomDetail();setTimeout(function(){var t=document.querySelector('#bdTable tbody td.bd-toggle');if(t)t.click();},1800);})() --wait 3400"
"inventory/product-sales-performance.png|${R}invmonthlysales|"
"inventory/item-history.png|${R}invitemhist&itemid=1243|"
"inventory/stock-movement-ledger.png|${R}invstckmovement|"
# --- qualifications ---
"qualifications/expiring-qualifications.png|${R}qualExpiring|"
"qualifications/expired-qualifications.png|${R}qualExpired|"
"qualifications/renewal-forecast.png|${R}qualRenewalForecast|"
"qualifications/qualification-matrix.png|${R}qualMatrix|"
)

FAIL=0; OK=0
for e in "${ENTRIES[@]}"; do
  IFS='|' read -r out path flags <<< "$e"
  echo ">> $out"
  # shellcheck disable=SC2086
  if node shot.js "$path" $WH --out "$DOCS/$out" $flags >/tmp/shot.log 2>&1; then
    sz=$(stat -c%s "$DOCS/$out" 2>/dev/null || echo 0)
    echo "   ok ($((sz/1024)) KB)"; OK=$((OK+1))
  else
    echo "   FAIL: $(tail -1 /tmp/shot.log)"; FAIL=$((FAIL+1))
  fi
done
echo "=== done: $OK ok, $FAIL failed ==="
