#!/bin/bash
# lfcs-drive-upload.sh — generic LFCS pricing pack uploader
#
# Uploads pricing-pack files from vault to Drive job folder, applying:
#   - canonical Drive subfolder routing (per pricing-checklist Phase 7)
#   - correct mimeType per file extension (gws CLI gotcha — see below)
#   - auto-share with Rocky's personal Gmail as Editor, no notification
#   - _v-CC / _v-CW filename convention preservation
#
# Usage:
#   bash scripts/lfcs/lfcs-drive-upload.sh \
#        "<vault job folder absolute path>" \
#        "<drive job folder root id>"
#
# Vault folder must contain:
#   02 - Scope and Pricing/02a - Quotes and Estimates/   <-- Tender Summary + cover + Inclusions-Exclusions + Submission-Cover
#   02 - Scope and Pricing/02b - BOQ and Rate Schedules/ <-- Pre-Pricing-Grill + Take-Off + Rate-Buildup
#
# Drive folder must already exist with canonical 11-section structure
# (lfcs-project-init creates this). This script auto-discovers the
# 02 - Scope & Pricing children by name.
#
# ─────────────────────────────────────────────────────────────────────
# GOTCHA discovered 2026-05-04 PM late on 2629 first run:
#
# `gws drive files create --params '{"name":..., "parents":[...], "mimeType":...}'`
# UPLOADS BYTES BUT IGNORES ALL 3 METADATA FIELDS. Files land in
# opsman.systems@gmail.com My Drive root with name="Untitled" + auto-detected
# mimeType (xlsx becomes application/x-zip, which Drive UI can't render as
# Excel). PDFs work because mimeType auto-detect on PDF magic bytes is correct.
#
# CORRECT PATTERN — pass metadata via --json (request body), NOT --params:
#
#   gws drive files create \
#       --upload "<path>" \
#       --json '{"name":"<n>","parents":["<id>"],"mimeType":"<mime>"}'
#
# This script bakes that pattern in.
# ─────────────────────────────────────────────────────────────────────

set -e

if [ "$#" -lt 2 ]; then
    echo "Usage: bash $0 <vault_job_dir> <drive_root_folder_id>"
    echo "Example: bash $0 \"HQ-Vault/.../Jobs/Upcoming/2629 - TCE - Erskine Park WWTP Slab\" 1fIkqU94QVppuEAaIiKA2hilrbvxdo4_V"
    exit 1
fi

VAULT_DIR="$1"
DRIVE_ROOT="$2"

export GOOGLE_WORKSPACE_CLI_CONFIG_DIR="${GOOGLE_WORKSPACE_CLI_CONFIG_DIR:-C:\\Users\\mclou\\.config\\gws-opsman}"
ROCKY_EMAIL="${ROCKY_EMAIL:-mcloughlinmichael.r@gmail.com}"

XLSX_MIME="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
PDF_MIME="application/pdf"
DOCX_MIME="application/vnd.openxmlformats-officedocument.wordprocessingml.document"

VAULT_02A="$VAULT_DIR/02 - Scope and Pricing/02a - Quotes and Estimates"
VAULT_02B="$VAULT_DIR/02 - Scope and Pricing/02b - BOQ and Rate Schedules"

# ─── Discover Drive subfolder IDs by name ──────────────────────────────
echo "Discovering Drive subfolder IDs under $DRIVE_ROOT..."
SCOPE_PRICING_ID=$(gws drive files list \
    --params "{\"q\":\"'$DRIVE_ROOT' in parents and name='02 - Scope & Pricing' and mimeType='application/vnd.google-apps.folder'\",\"fields\":\"files(id)\"}" 2>&1 \
    | python -c "import json,sys; data=sys.stdin.read(); start=data.find('{'); print(json.loads(data[start:])['files'][0]['id'])")

QUOTES_ID=$(gws drive files list \
    --params "{\"q\":\"'$SCOPE_PRICING_ID' in parents and name='Quotes & Estimates' and mimeType='application/vnd.google-apps.folder'\",\"fields\":\"files(id)\"}" 2>&1 \
    | python -c "import json,sys; data=sys.stdin.read(); start=data.find('{'); print(json.loads(data[start:])['files'][0]['id'])")

BOQ_ID=$(gws drive files list \
    --params "{\"q\":\"'$SCOPE_PRICING_ID' in parents and name='BOQ & Rate Schedules' and mimeType='application/vnd.google-apps.folder'\",\"fields\":\"files(id)\"}" 2>&1 \
    | python -c "import json,sys; data=sys.stdin.read(); start=data.find('{'); print(json.loads(data[start:])['files'][0]['id'])")

echo "  02 - Scope & Pricing: $SCOPE_PRICING_ID"
echo "  Quotes & Estimates:   $QUOTES_ID"
echo "  BOQ & Rate Schedules: $BOQ_ID"
echo ""

# ─── Atomic upload + share ─────────────────────────────────────────────
upload_and_share() {
    local file_path="$1"
    local parent_id="$2"
    local file_name=$(basename "$file_path")

    if [ ! -f "$file_path" ]; then
        echo "  SKIP (not found): $file_name"
        return 0
    fi

    # Pick mimeType from extension
    local mime
    case "$file_name" in
        *.xlsx) mime="$XLSX_MIME" ;;
        *.pdf)  mime="$PDF_MIME" ;;
        *.docx) mime="$DOCX_MIME" ;;
        *)      mime="application/octet-stream" ;;
    esac

    echo "----- Uploading: $file_name (mime: ${mime##*/}) -----"
    local result=$(gws drive files create \
        --upload "$file_path" \
        --json "{\"name\":\"$file_name\",\"parents\":[\"$parent_id\"],\"mimeType\":\"$mime\"}" 2>&1)

    local file_id=$(echo "$result" | python -c "import json,sys; data=sys.stdin.read(); start=data.find('{'); print(json.loads(data[start:])['id'])" 2>/dev/null)

    if [ -z "$file_id" ]; then
        echo "  UPLOAD FAILED. Raw result:"
        echo "$result"
        return 1
    fi

    echo "  uploaded id=$file_id"

    # Share with Rocky as Editor, no notification
    gws drive permissions create \
        --json "{\"role\":\"writer\",\"type\":\"user\",\"emailAddress\":\"$ROCKY_EMAIL\"}" \
        --params "{\"fileId\":\"$file_id\",\"sendNotificationEmail\":false,\"supportsAllDrives\":true}" >/dev/null 2>&1

    echo "  shared with $ROCKY_EMAIL (Editor, no notification)"
    echo "  https://drive.google.com/file/d/$file_id/view"
    echo ""
}

# ─── BOQ & Rate Schedules ──────────────────────────────────────────────
for f in "$VAULT_02B"/*Pre-Pricing-Grill*.pdf "$VAULT_02B"/*Take-Off*.xlsx "$VAULT_02B"/*Rate-Buildup*.xlsx; do
    upload_and_share "$f" "$BOQ_ID"
done

# ─── Quotes & Estimates ────────────────────────────────────────────────
for f in "$VAULT_02A"/*Tender-Summary_*.xlsx "$VAULT_02A"/*Tender-Summary-Cover*.pdf "$VAULT_02A"/*Inclusions-Exclusions*.pdf "$VAULT_02A"/*Submission-Cover*.pdf; do
    upload_and_share "$f" "$QUOTES_ID"
done

echo "Done. All pricing-pack files uploaded + shared."
