set shell := ["bash", "-euo", "pipefail", "-c"]

project := "Hydraulophone.xcodeproj"
scheme := "Hydraulophone"
xcode_developer_dir := "/Applications/Xcode.app/Contents/Developer"
simulator_device := env_var_or_default("HYDRAULOPHONE_SIMULATOR", "iPhone 18 Pro")
simulator_os := env_var_or_default("HYDRAULOPHONE_SIMULATOR_OS", "27.0")
simulator_destination := "platform=iOS Simulator,name=" + simulator_device + ",OS=" + simulator_os
simulator_derived_data := ".build/ios-simulator"
device_derived_data := ".build/ios-device"
mac_derived_data := ".build/mac"

default: check

# Regenerate the Xcode project from the checked-in project specification.
generate:
    ./Scripts/generate-project --force

# Explicit alias for replacing the existing generated project.
regenerate: generate

# Build recipes create the project and generated config only when absent.
[private]
_ensure-project:
    @if [[ ! -d '{{project}}' ]]; then ./Scripts/generate-project; fi
    @if [[ ! -f .build/generated/LastFMBuildConfiguration.swift ]]; then python3 Scripts/generate_lastfm_build_configuration.py; fi

# Run Swift-format's strict source linter over app, core, and test code.
lint:
    swift format lint --recursive --strict Sources Tests

# Run the package-level fixture tests without requiring a live InnerTube request.
test:
    swift test

# Compile the universal iPhone/iPad app for a generic simulator destination.
compile: _ensure-project
    DEVELOPER_DIR={{xcode_developer_dir}} xcodebuild build -project {{project}} -scheme {{scheme}} -destination 'generic/platform=iOS Simulator' CODE_SIGN_IDENTITY=- CODE_SIGNING_REQUIRED=YES CODE_SIGNING_ALLOWED=YES

# Build and launch the Mac Catalyst app with its Keychain entitlement.
mac: _ensure-project
    #!/usr/bin/env bash
    set -euo pipefail
    export DEVELOPER_DIR="{{xcode_developer_dir}}"
    development_team="${HYDRAULOPHONE_DEVELOPMENT_TEAM:-}"
    if [[ -z "$development_team" ]]; then
      development_team="$(python3 Scripts/read_development_team.py)"
    fi
    build_args=(
      build
      -project "{{project}}"
      -scheme "{{scheme}}"
      -destination 'platform=macOS,variant=Mac Catalyst'
      -derivedDataPath "{{mac_derived_data}}"
      "DEVELOPMENT_TEAM=${development_team}"
      "CODE_SIGN_IDENTITY=Apple Development"
      CODE_SIGN_STYLE=Automatic
      CODE_SIGNING_REQUIRED=YES
      CODE_SIGNING_ALLOWED=YES
    )
    if [[ "${HYDRAULOPHONE_ALLOW_PROVISIONING_UPDATES:-1}" == "1" ]]; then
      build_args+=(-allowProvisioningUpdates)
    fi
    xcodebuild "${build_args[@]}"
    open -n -a "$PWD/{{mac_derived_data}}/Build/Products/Debug-maccatalyst/Hydraulophone.app"

# Package an unnotarized Apple Silicon DMG with the existing development identity.
# Infers the signing team like `just mac`; preserves the Keychain entitlement.
dmg version build: _ensure-project
    DEVELOPER_DIR={{quote(xcode_developer_dir)}} python3 Scripts/release_macos.py {{quote(version)}} {{quote(build)}}

# Backwards-compatible alias for the compile recipe.
build: compile

# Build, install, and launch on a simulator; includes the bundled public playback key.
simulator: _ensure-project
    #!/usr/bin/env bash
    set -euo pipefail
    public_jnn_key="${SIMCTL_CHILD_HYDRAULOPHONE_PUBLIC_JNN_KEY:-}"
    if [[ -z "$public_jnn_key" ]]; then
      public_jnn_key="$(python3 Scripts/read_public_jnn_key.py)"
    fi
    devicehub_app="{{xcode_developer_dir}}/../Applications/DeviceHub.app"
    simulator_app="{{xcode_developer_dir}}/Applications/Simulator.app"
    if [[ -x "$devicehub_app/Contents/MacOS/DeviceHub" ]]; then
      open "$devicehub_app" >/dev/null 2>&1 || true
    elif [[ -x "$simulator_app/Contents/MacOS/Simulator" ]]; then
      open "$simulator_app" >/dev/null 2>&1 || true
    fi
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl boot "{{simulator_device}}" 2>/dev/null || true
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl bootstatus "{{simulator_device}}" -b
    DEVELOPER_DIR={{xcode_developer_dir}} xcodebuild build -project {{project}} -scheme {{scheme}} -destination '{{simulator_destination}}' -derivedDataPath '{{simulator_derived_data}}' CODE_SIGN_IDENTITY=- CODE_SIGNING_REQUIRED=YES CODE_SIGNING_ALLOWED=YES CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM=
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl install "{{simulator_device}}" "{{simulator_derived_data}}/Build/Products/Debug-iphonesimulator/Hydraulophone.app"
    SIMCTL_CHILD_HYDRAULOPHONE_PUBLIC_JNN_KEY="$public_jnn_key" DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl launch --terminate-running-process "{{simulator_device}}" com.hydraulophone.app

# Build and launch the CarPlay-enabled app, then point to Device Hub's menu search.
carplay-simulator: simulator
    @printf 'CarPlay Simulator is integrated into Device Hub in Xcode 27. Use Device Hub Help > search for “CarPlay” to locate the connection command for the selected iPhone simulator.\n'

# Install and launch on a connected iPhone, bundling the attributed public playback key.
# Infers its Team ID from local Apple Development certificates.
device-install: _ensure-project
    #!/usr/bin/env bash
    set -euo pipefail
    export DEVELOPER_DIR="{{xcode_developer_dir}}"
    device_id="$(python3 Scripts/select_connected_iphone.py)"
    printf 'Using iPhone: %s\n' "$device_id"
    public_jnn_key="${DEVICECTL_CHILD_HYDRAULOPHONE_PUBLIC_JNN_KEY:-}"
    if [[ -z "$public_jnn_key" ]]; then
      public_jnn_key="$(python3 Scripts/read_public_jnn_key.py)"
    fi
    export DEVICECTL_CHILD_HYDRAULOPHONE_PUBLIC_JNN_KEY="$public_jnn_key"
    device_entitlements="Resources/Hydraulophone.Device.entitlements"
    case "${HYDRAULOPHONE_DEVICE_CARPLAY:-0}" in
      0) ;;
      1) device_entitlements="Resources/Hydraulophone.entitlements" ;;
      *) printf 'HYDRAULOPHONE_DEVICE_CARPLAY must be 0 or 1.\n' >&2; exit 2 ;;
    esac
    if /usr/libexec/PlistBuddy -c 'Print :com.apple.developer.carplay-audio' "$device_entitlements" 2>/dev/null | grep -qx true; then
      printf 'Including CarPlay entitlement for device build.\n'
    else
      printf 'Omitting CarPlay entitlement for device build.\n'
    fi
    development_team="${HYDRAULOPHONE_DEVELOPMENT_TEAM:-}"
    if [[ -z "$development_team" ]]; then
      development_team="$(python3 Scripts/read_development_team.py)"
    fi
    build_args=(build -project "{{project}}" -scheme "{{scheme}}" -destination "platform=iOS,id=${device_id}" -derivedDataPath "{{device_derived_data}}")
    build_args+=("DEVELOPMENT_TEAM=${development_team}")
    build_args+=("CODE_SIGN_ENTITLEMENTS=${device_entitlements}")
    if [[ "${HYDRAULOPHONE_ALLOW_PROVISIONING_UPDATES:-1}" == "1" ]]; then
      build_args+=(-allowProvisioningUpdates)
    fi
    xcodebuild "${build_args[@]}"
    app_path="{{device_derived_data}}/Build/Products/Debug-iphoneos/Hydraulophone.app"
    xcrun devicectl device install app --device "$device_id" "$app_path"
    xcrun devicectl device process launch --terminate-existing --device "$device_id" com.hydraulophone.app

# Relaunch the installed app with its public playback key and stream its debug console.
device-console:
    #!/usr/bin/env bash
    set -euo pipefail
    export DEVELOPER_DIR="{{xcode_developer_dir}}"
    device_id="$(python3 Scripts/select_connected_iphone.py)"
    public_jnn_key="${DEVICECTL_CHILD_HYDRAULOPHONE_PUBLIC_JNN_KEY:-}"
    if [[ -z "$public_jnn_key" ]]; then
      public_jnn_key="$(python3 Scripts/read_public_jnn_key.py)"
    fi
    export DEVICECTL_CHILD_HYDRAULOPHONE_PUBLIC_JNN_KEY="$public_jnn_key"
    xcrun devicectl device process launch --console --terminate-existing --device "$device_id" com.hydraulophone.app

# Build and launch deterministic fixture data without reading Keychain or
# making any network request. Useful for safe accessibility inspection.
simulator-offline: _ensure-project
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl boot "{{simulator_device}}" 2>/dev/null || true
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl bootstatus "{{simulator_device}}" -b
    DEVELOPER_DIR={{xcode_developer_dir}} xcodebuild build -project {{project}} -scheme {{scheme}} -destination '{{simulator_destination}}' -derivedDataPath '{{simulator_derived_data}}' CODE_SIGN_IDENTITY=- CODE_SIGNING_REQUIRED=YES CODE_SIGNING_ALLOWED=YES CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM=
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl install "{{simulator_device}}" "{{simulator_derived_data}}/Build/Products/Debug-iphonesimulator/Hydraulophone.app"
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl launch --terminate-running-process "{{simulator_device}}" com.hydraulophone.app -HydraulophoneOfflineFixture

# Run the test target on an installed iPhone simulator.
simulator-test: _ensure-project
    DEVELOPER_DIR={{xcode_developer_dir}} xcodebuild test -project {{project}} -scheme {{scheme}} -destination '{{simulator_destination}}' CODE_SIGN_IDENTITY=- CODE_SIGNING_REQUIRED=YES CODE_SIGNING_ALLOWED=YES CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM=

# Run the bounded, opt-in authenticated search/playlists/playback diagnostic.
# This target requires a real Keychain session already present in the app.
simulator-smoke: _ensure-project
    #!/usr/bin/env bash
    set -euo pipefail
    log_file="${HYDRAULOPHONE_SMOKE_LOG:-.build/simulator-smoke.log}"
    smoke_args=(-HydraulophoneLiveSmoke)
    smoke_high="${HYDRAULOPHONE_SMOKE_HIGH:-0}"
    if [[ "${HYDRAULOPHONE_SMOKE_EXTENDED:-0}" == "1" ]]; then
      smoke_args+=(-HydraulophoneExtendedSmoke)
    fi
    if [[ "$smoke_high" == "1" ]]; then
      smoke_args+=(-HydraulophoneHighPlayerSmoke)
    fi
    if [[ "${HYDRAULOPHONE_SMOKE_CATALOG:-0}" == "1" ]]; then
      smoke_args=(-HydraulophoneCatalogSmoke)
    fi
    if [[ "${HYDRAULOPHONE_SMOKE_TRACK_ACTIONS:-0}" == "1" ]]; then
      smoke_args=(-HydraulophoneLiveSmoke -HydraulophoneTrackActionsSmoke)
    fi
    if [[ "${HYDRAULOPHONE_SMOKE_PERSONAL_MIXES:-0}" == "1" ]]; then
      smoke_args=(-HydraulophoneLiveSmoke -HydraulophonePersonalMixesSmoke)
    fi
    if [[ "${HYDRAULOPHONE_SMOKE_LISTENING_QUALITY:-0}" == "1" ]]; then
      smoke_args=(-HydraulophoneLiveSmoke -HydraulophoneListeningQualitySmoke)
    fi
    if [[ "${HYDRAULOPHONE_SMOKE_DOWNLOADS:-0}" == "1" ]]; then
      smoke_args=(-HydraulophoneLiveSmoke -HydraulophoneDownloadSmoke)
      if [[ "${HYDRAULOPHONE_DOWNLOAD_QUALITY:-high}" == "standard" ]]; then
        smoke_args+=(-HydraulophoneDownloadStandard)
      fi
    fi
    mkdir -p "$(dirname "$log_file")"
    : > "$log_file"
    log_pid=""
    app_launched=0
    cleanup() {
      local exit_status=$?
      if [[ "$exit_status" -ne 0 && "$app_launched" -eq 1 ]]; then
        DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl terminate "{{simulator_device}}" com.hydraulophone.app 2>/dev/null || true
      fi
      if [[ -n "$log_pid" ]]; then
        kill "$log_pid" 2>/dev/null || true
        wait "$log_pid" 2>/dev/null || true
      fi
      printf 'Smoke log: %s\n' "$log_file"
    }
    cancel() {
      exit 130
    }
    trap 'cleanup' EXIT
    trap 'cancel' INT TERM
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl boot "{{simulator_device}}" 2>/dev/null || true
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl bootstatus "{{simulator_device}}" -b
    DEVELOPER_DIR={{xcode_developer_dir}} xcodebuild build -project {{project}} -scheme {{scheme}} -destination '{{simulator_destination}}' -derivedDataPath '{{simulator_derived_data}}' CODE_SIGN_IDENTITY=- CODE_SIGNING_REQUIRED=YES CODE_SIGNING_ALLOWED=YES CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM=
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl install "{{simulator_device}}" "{{simulator_derived_data}}/Build/Products/Debug-iphonesimulator/Hydraulophone.app"
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl spawn "{{simulator_device}}" log stream --style compact --level debug --predicate 'subsystem == "com.hydraulophone"' >"$log_file" 2>&1 &
    log_pid=$!
    sleep 1
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl launch --terminate-running-process "{{simulator_device}}" com.hydraulophone.app "${smoke_args[@]}"
    app_launched=1
    deadline_seconds=180
    if [[ "$smoke_high" == "1" ]]; then
      deadline_seconds=300
    fi
    deadline=$((SECONDS + deadline_seconds))
    while (( SECONDS < deadline )); do
      if grep -q 'smoke outcome=cancelled' "$log_file"; then
        printf 'Smoke outcome: cancelled\n'
        exit 1
      fi
      if grep -q 'smoke outcome=inconclusive' "$log_file"; then
        printf 'Smoke outcome: inconclusive (required evidence was unavailable)\n'
        exit 2
      fi
      if grep -q 'smoke outcome=failure' "$log_file"; then
        printf 'Smoke outcome: failure\n'
        exit 1
      fi
      if grep -q 'smoke outcome=skipped' "$log_file"; then
        printf 'Smoke outcome: skipped (authenticated session is required)\n'
        exit 2
      fi
      if [[ "$smoke_high" == "1" ]] && grep -q 'smoke outcome=success mode=high' "$log_file"; then
        printf 'Smoke outcome: High success\n'
        exit 0
      fi
      if [[ "$smoke_high" != "1" ]] && grep -q 'smoke outcome=success' "$log_file"; then
        printf 'Smoke outcome: success\n'
        exit 0
      fi
      sleep 1
    done
    printf 'Smoke outcome: timeout after %s seconds\n' "$deadline_seconds"
    exit 1

# Opt-in sustained playback, pause/resume, seek, and next-track check.
simulator-smoke-extended:
    HYDRAULOPHONE_SMOKE_EXTENDED=1 just simulator-smoke

# Run production High Opus playback, proof generation, exact-time unbuffered
# seeks, pause/resume, and High/Standard quality switches. Requires an
# authenticated simulator Keychain session. The public JNN key is loaded from
# the attributed public client key in Config/ unless explicitly supplied in the environment.
simulator-smoke-high:
    #!/usr/bin/env bash
    set -euo pipefail
    public_jnn_key="${SIMCTL_CHILD_HYDRAULOPHONE_PUBLIC_JNN_KEY:-}"
    if [[ -z "$public_jnn_key" ]]; then
      public_jnn_key="$(python3 Scripts/read_public_jnn_key.py)"
    fi
    SIMCTL_CHILD_HYDRAULOPHONE_PUBLIC_JNN_KEY="$public_jnn_key" HYDRAULOPHONE_SMOKE_HIGH=1 just simulator-smoke

# Opt-in, read-only catalog first/continuation-page checks; no media playback.
simulator-smoke-catalog:
    HYDRAULOPHONE_SMOKE_CATALOG=1 just simulator-smoke

# Opt-in, read-only search -> linked artist -> linked album navigation check.
simulator-smoke-track-actions:
    HYDRAULOPHONE_SMOKE_TRACK_ACTIONS=1 just simulator-smoke

# Opt-in, read-only Home -> personal mix -> track continuation check.
simulator-smoke-personal-mixes:
    HYDRAULOPHONE_SMOKE_PERSONAL_MIXES=1 just simulator-smoke

# Opt-in normalization, successor caching and bundled-key playback diagnostic.
simulator-smoke-listening-quality:
    HYDRAULOPHONE_SMOKE_LISTENING_QUALITY=1 just simulator-smoke

# Opt-in single-track download, local artwork, offline playback/seek and restore.
# Set HYDRAULOPHONE_DOWNLOAD_QUALITY=standard to check AAC instead of Opus.
simulator-smoke-downloads:
    #!/usr/bin/env bash
    set -euo pipefail
    public_jnn_key="${SIMCTL_CHILD_HYDRAULOPHONE_PUBLIC_JNN_KEY:-}"
    if [[ -z "$public_jnn_key" ]]; then
      public_jnn_key="$(python3 Scripts/read_public_jnn_key.py)"
    fi
    SIMCTL_CHILD_HYDRAULOPHONE_PUBLIC_JNN_KEY="$public_jnn_key" HYDRAULOPHONE_SMOKE_DOWNLOADS=1 just simulator-smoke

# Run the opt-in XCUITest navigation loop. It never captures screenshots.
simulator-smoke-ui: _ensure-project
    DEVELOPER_DIR={{xcode_developer_dir}} TEST_RUNNER_HYDRAULOPHONE_LIVE_UI=1 xcodebuild test -project {{project}} -scheme {{scheme}} -destination '{{simulator_destination}}' -only-testing:HydraulophoneUITests/HydraulophoneLiveSmokeUITests/testLiveAuthenticatedSearchPlaylistPlayback CODE_SIGN_IDENTITY=- CODE_SIGNING_REQUIRED=YES CODE_SIGNING_ALLOWED=YES CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM=

# Follow Hydraulophone's focused authentication logs from the configured simulator.
simulator-logs:
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl spawn "{{simulator_device}}" log stream --style compact --level info --predicate 'subsystem == "com.hydraulophone"'

# Read only recent Hydraulophone subsystem messages; credentials are not logged.
simulator-logs-recent:
    DEVELOPER_DIR={{xcode_developer_dir}} xcrun simctl spawn "{{simulator_device}}" log show --info --last 15m --style compact --predicate 'subsystem == "com.hydraulophone"'

# Run the fast checks and simulator-compilable app build.
check: lint test compile
