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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="$ROOT_DIR/.env"
ENV_EXAMPLE="$ROOT_DIR/.env.example"
RUNTIME_DIR="$ROOT_DIR/runtime"
DB_INIT_DIR="$RUNTIME_DIR/db-init"
CRASH_CONFIG="$RUNTIME_DIR/crash-config.php"
BUILD_CONFIG="$RUNTIME_DIR/build-config.php"
OTA_DIR="$RUNTIME_DIR/ota-artifacts"

SRC_SCHEMA="$ROOT_DIR/../examples/crash_reporter/backend/sql/schema.mariadb.sql"
SRC_MIG_004="$ROOT_DIR/../examples/crash_reporter/backend/sql/migrations/004_ticket_workflow.sql"
SRC_MIG_005="$ROOT_DIR/../examples/crash_reporter/backend/sql/migrations/005_ticket_attachments.sql"
SRC_MIG_060="$ROOT_DIR/runtime/db-init/060_build_ecosystem.sql"

if ! command -v docker >/dev/null 2>&1; then
  echo "docker not found in PATH"
  exit 1
fi

if ! docker compose version >/dev/null 2>&1; then
  echo "docker compose plugin is required"
  exit 1
fi

if [[ ! -f "$ENV_FILE" ]]; then
  cp "$ENV_EXAMPLE" "$ENV_FILE"
  echo "Created .env from .env.example"
fi

set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

mkdir -p "$DB_INIT_DIR" "$OTA_DIR"

cat >"$CRASH_CONFIG" <<EOF
<?php
return [
    'app_name' => 'Android Cast Crashes',
    'base_path' => '/app/androidcast_project/crashes',
    'session_name' => 'ac_crash_sess',
    'session_cookie_path' => '/app/androidcast_project',
    'db' => [
        'driver' => 'mysql',
        'sqlite_path' => __DIR__ . '/../data/crashes.sqlite',
        'mysql' => [
            'host' => 'mariadb',
            'port' => 3306,
            'socket' => '',
            'database' => '${MARIADB_DATABASE}',
            'username' => '${MARIADB_USER}',
            'password' => '${MARIADB_PASSWORD}',
            'charset' => 'utf8mb4',
        ],
    ],
    'debug' => true,
    'rbac' => [
        'default_company_slug' => 'default',
        'default_company_id' => 1,
    ],
];
EOF

cat >"$BUILD_CONFIG" <<EOF
<?php
return [
    'app_name' => 'Android Cast Builder',
    'base_path' => '/app/androidcast_project/build',
    'session_name' => 'ac_crash_sess',
    'session_cookie_path' => '/app/androidcast_project',
    'db' => [
        'driver' => 'mysql',
        'sqlite_path' => __DIR__ . '/../../crash_reporter/backend/data/crashes.sqlite',
        'mysql' => [
            'host' => 'mariadb',
            'port' => 3306,
            'socket' => '',
            'database' => '${MARIADB_DATABASE}',
            'username' => '${MARIADB_USER}',
            'password' => '${MARIADB_PASSWORD}',
            'charset' => 'utf8mb4',
        ],
    ],
    'debug' => true,
    'rbac' => [
        'default_company_slug' => 'default',
        'default_company_id' => 1,
    ],
    'build' => [
        'docker_image' => 'androidcast-ci:latest',
        'ci_version' => '00.01.00.1000',
        'repo_root' => '/workspace',
        'artifacts_root' => '/workspace/out/builds',
        'ota_mount' => '/workspace/orchestration/runtime/ota-artifacts',
        'ota_base_url' => '${PUBLIC_BASE_URL}',
        'runner_script' => '/workspace/scripts/docker-build-runner.sh',
        'pipeline_config' => '/workspace/build.config.yml',
        'default_channels' => ['stable', 'staging', 'dev', 'nightly'],
    ],
    'links' => [
        'hub' => '/app/androidcast_project/',
        'crashes' => '/app/androidcast_project/crashes/',
        'git' => '/app/androidcast_project/git/',
        'tickets' => '/app/androidcast_project/crashes/?view=tickets',
    ],
];
EOF

SRC_MIG_070="$ROOT_DIR/runtime/db-init/070_graph_ecosystem.sql"
SRC_MIG_007="$ROOT_DIR/runtime/db-init/007_remote_access.sql"

write_migration_with_db() {
  local src="$1"
  local dest="$2"
  local tmp
  tmp="$(mktemp)"
  {
    echo "USE \`${MARIADB_DATABASE}\`;"
    cat "$src"
  } >"$tmp"
  mv "$tmp" "$dest"
}

cp "$SRC_SCHEMA" "$DB_INIT_DIR/010_schema.sql"
write_migration_with_db "$SRC_MIG_004" "$DB_INIT_DIR/040_ticket_workflow.sql"
write_migration_with_db "$SRC_MIG_005" "$DB_INIT_DIR/050_ticket_attachments.sql"
write_migration_with_db "$SRC_MIG_060" "$DB_INIT_DIR/060_build_ecosystem.sql"
write_migration_with_db "$SRC_MIG_070" "$DB_INIT_DIR/070_graph_ecosystem.sql"
write_migration_with_db "$SRC_MIG_007" "$DB_INIT_DIR/007_remote_access.sql"

echo "Pulling images..."
docker compose -f "$ROOT_DIR/docker-compose.yml" pull landing-fe gitea-fe crashes-fe build-fe mariadb gitea || true

echo "Starting/updating stack..."
docker compose -f "$ROOT_DIR/docker-compose.yml" up -d --build --remove-orphans --force-recreate

echo
echo "Stack is up."
echo "Landing: ${PUBLIC_BASE_URL}/app/androidcast_project/"
echo "Gitea (direct FE): http://localhost:${GITEA_FE_PORT}/app/androidcast_project/git/"
echo "Crashes (direct FE): http://localhost:${CRASHES_FE_PORT}/app/androidcast_project/crashes/"
echo "Graphs (via landing): ${PUBLIC_BASE_URL}/app/androidcast_project/graphs/"
echo "Builder (direct FE): http://localhost:${BUILD_FE_PORT:-8083}/app/androidcast_project/build/"
echo "Shared login: same user/password as Crashes (session cookie path /app/androidcast_project)"
echo
docker compose -f "$ROOT_DIR/docker-compose.yml" ps
