#!/bin/bash
# One-shot project bootstrap: creates the AI meta-files + folder structure,
# and wires the real Hilt + Retrofit + Coroutines/StateFlow stack into Gradle
# (not just documents it). Safe to re-run: every step is skip-if-already-done,
# so it never overwrites something you've since customized.
#
# Usage:
#   ./init_skeleton.sh [new.package.name]
#
# With no argument, it wires the stack for whatever package the project
# already uses. With an argument, it also renames the app's package
# (namespace, applicationId, directory layout, package/import declarations)
# to the one you give it — e.g.:
#
#   ./init_skeleton.sh com.acme.widget

set -euo pipefail

APP_GRADLE="app/build.gradle.kts"
ROOT_GRADLE="build.gradle.kts"
TOML="gradle/libs.versions.toml"
MANIFEST="app/src/main/AndroidManifest.xml"
SETTINGS_GRADLE="settings.gradle.kts"

if [ ! -f "$APP_GRADLE" ]; then
  echo "Can't find $APP_GRADLE — run this from the project root."
  exit 1
fi

CURRENT_PKG=$(grep -oE 'namespace = "[^"]+"' "$APP_GRADLE" | head -1 | sed -E 's/namespace = "(.*)"/\1/')
if [ -z "$CURRENT_PKG" ]; then
  echo "Could not read a 'namespace = \"...\"' line from $APP_GRADLE."
  exit 1
fi

NEW_PKG="${1:-$CURRENT_PKG}"
CURRENT_PATH=$(echo "$CURRENT_PKG" | tr '.' '/')
NEW_PATH=$(echo "$NEW_PKG" | tr '.' '/')
SRC_ROOT="app/src/main/java"
OLD_BASE="$SRC_ROOT/$CURRENT_PATH"
NEW_BASE="$SRC_ROOT/$NEW_PATH"

# Every module that can carry package-named source. core-ui/core-utils/core-network/auth
# only exist after step 2 has run at least once, so most of these are no-ops on a first
# run against a vanilla single-module template — that's expected, not an error.
MODULE_SRC_ROOTS=(
  "app/src/main/java"
  "core-ui/src/main/java"
  "core-utils/src/main/java"
  "core-network/src/main/java"
  "auth/src/main/java"
)

# --- helpers -----------------------------------------------------------------

# insert TEXT (may be multi-line) on the line right after the first line
# containing ANCHOR. TEXT is passed through a temp file + awk getline rather
# than -v, because BSD/macOS awk rejects embedded newlines in a -v string.
insert_after() {
  local file="$1" anchor="$2" text="$3"
  local tmp; tmp=$(mktemp)
  printf '%s\n' "$text" > "$tmp"
  awk -v anchor="$anchor" -v insfile="$tmp" '
    BEGIN { while ((getline line < insfile) > 0) block = block line "\n" }
    { print }
    !done && index($0, anchor) > 0 { printf "%s", block; done=1 }
  ' "$file" > "$file.tmp" && mv "$file.tmp" "$file"
  rm -f "$tmp"
}

# insert TEXT (may be multi-line) on the line right before the first line
# containing ANCHOR. See insert_after for why this goes through a temp file.
insert_before() {
  local file="$1" anchor="$2" text="$3"
  local tmp; tmp=$(mktemp)
  printf '%s\n' "$text" > "$tmp"
  awk -v anchor="$anchor" -v insfile="$tmp" '
    BEGIN { while ((getline line < insfile) > 0) block = block line "\n" }
    !done && index($0, anchor) > 0 { printf "%s", block; done=1 }
    { print }
  ' "$file" > "$file.tmp" && mv "$file.tmp" "$file"
  rm -f "$tmp"
}

# replace the first line containing ANCHOR with TEXT (may be multi-line) instead
# of the original line. See insert_after for why this goes through a temp file.
replace_line() {
  local file="$1" anchor="$2" text="$3"
  local tmp; tmp=$(mktemp)
  printf '%s\n' "$text" > "$tmp"
  awk -v anchor="$anchor" -v insfile="$tmp" '
    BEGIN { while ((getline line < insfile) > 0) block = block line "\n" }
    !done && index($0, anchor) > 0 { printf "%s", block; done=1; next }
    { print }
  ' "$file" > "$file.tmp" && mv "$file.tmp" "$file"
  rm -f "$tmp"
}

# ------------------------------------------------------------------------------
# 1. Rename the package, if requested
# ------------------------------------------------------------------------------

RENAMED=false
if [ "$NEW_PKG" != "$CURRENT_PKG" ]; then
  RENAMED=true
  echo "Renaming package $CURRENT_PKG -> $NEW_PKG ..."

  if [ ! -d "$OLD_BASE" ]; then
    echo "Expected existing source at $OLD_BASE, not found — aborting rename."
    exit 1
  fi
  if [ -d "$NEW_BASE" ] && [ "$OLD_BASE" != "$NEW_BASE" ]; then
    echo "$NEW_BASE already exists — aborting so nothing gets overwritten."
    exit 1
  fi

  CURRENT_PKG_RE=$(echo "$CURRENT_PKG" | sed 's/\./\\./g')

  # app's source is guaranteed to exist (checked above); the core-*/auth module
  # roots only exist once step 2 has created those modules, so skip whichever
  # aren't there yet rather than treating a missing one as an error.
  for MODULE_ROOT in "${MODULE_SRC_ROOTS[@]}"; do
    MODULE_OLD_BASE="$MODULE_ROOT/$CURRENT_PATH"
    [ -d "$MODULE_OLD_BASE" ] || continue
    MODULE_NEW_BASE="$MODULE_ROOT/$NEW_PATH"

    mkdir -p "$(dirname "$MODULE_NEW_BASE")"
    mv "$MODULE_OLD_BASE" "$MODULE_NEW_BASE"

    find "$MODULE_NEW_BASE" -name "*.kt" -print0 | xargs -0 sed -i.bak \
      -e "s/package $CURRENT_PKG_RE/package $NEW_PKG/" \
      -e "s/import $CURRENT_PKG_RE/import $NEW_PKG/g"
    find "$MODULE_NEW_BASE" -name "*.bak" -delete
  done

  # Each library module's own namespace is "$CURRENT_PKG.<suffix>" (e.g.
  # "...core.ui") — a prefix match, since the suffix doesn't change.
  for MODULE_GRADLE in core-ui/build.gradle.kts core-utils/build.gradle.kts core-network/build.gradle.kts auth/build.gradle.kts; do
    [ -f "$MODULE_GRADLE" ] || continue
    sed -i.bak -E "s/namespace = \"$CURRENT_PKG_RE\\./namespace = \"$NEW_PKG./" "$MODULE_GRADLE"
    rm -f "$MODULE_GRADLE.bak"
  done

  for TEST_ROOT in "app/src/androidTest/java" "app/src/test/java"; do
    OLD_TEST_BASE="$TEST_ROOT/$CURRENT_PATH"
    if [ -d "$OLD_TEST_BASE" ]; then
      NEW_TEST_BASE="$TEST_ROOT/$NEW_PATH"
      mkdir -p "$(dirname "$NEW_TEST_BASE")"
      mv "$OLD_TEST_BASE" "$NEW_TEST_BASE"
      find "$NEW_TEST_BASE" -name "*.kt" -print0 | xargs -0 sed -i.bak \
        -e "s/package $CURRENT_PKG_RE/package $NEW_PKG/" \
        -e "s/import $CURRENT_PKG_RE/import $NEW_PKG/g"
      find "$NEW_TEST_BASE" -name "*.bak" -delete
    fi
  done

  sed -i.bak -E "s/namespace = \"$CURRENT_PKG\"/namespace = \"$NEW_PKG\"/" "$APP_GRADLE"
  sed -i.bak -E "s/applicationId = \"$CURRENT_PKG\"/applicationId = \"$NEW_PKG\"/" "$APP_GRADLE"
  rm -f "$APP_GRADLE.bak"
fi

PKG="$NEW_PKG"
BASE_PKG="$NEW_BASE"

# ------------------------------------------------------------------------------
# 2. Directory structure (safe to re-run — mkdir -p is a no-op if already there)
# ------------------------------------------------------------------------------

echo "Ensuring directory structure..."
mkdir -p "$BASE_PKG/features/dummy/data"
mkdir -p "$BASE_PKG/features/dummy/domain"
mkdir -p "$BASE_PKG/features/dummy/presentation"
mkdir -p "docs/ai"

# ------------------------------------------------------------------------------
# 2b. Fixed module layout: :core-ui, :core-utils, :core-network, :auth.
#     core-ui/core-network hold code every project needs (theme + shared
#     widgets; Retrofit/OkHttp wiring); core-utils is an empty home for future
#     cross-feature helpers; auth is an empty, wired Gradle boundary (no
#     backend or session model exists yet, so no login/signup UI is generated —
#     see auth/README.md). Every other feature stays inside :app, generated by
#     scripts/new_feature.sh exactly as before. Each module is independently
#     skip-if-exists, like every other step here.
# ------------------------------------------------------------------------------

if ! grep -q '^android-library' "$TOML" 2>/dev/null; then
  echo "Wiring the android-library plugin..."
  insert_after "$TOML" '[plugins]' 'android-library = { id = "com.android.library", version.ref = "agp" }'
  insert_after "$ROOT_GRADLE" 'alias(libs.plugins.android.application) apply false' '    alias(libs.plugins.android.library) apply false'
fi

for MODULE_NAME in core-ui core-utils core-network auth; do
  if ! grep -q "\"$MODULE_NAME\"" "$SETTINGS_GRADLE" 2>/dev/null; then
    insert_after "$SETTINGS_GRADLE" 'include(":app")' "include(\":$MODULE_NAME\")"
    echo "  added: :$MODULE_NAME to $SETTINGS_GRADLE"
  fi
done

if [ ! -f "core-ui/build.gradle.kts" ]; then
  mkdir -p "core-ui/src/main/java/$NEW_PATH/ui/theme"
  mkdir -p "core-ui/src/main/java/$NEW_PATH/shared_widgets"
  mkdir -p "core-ui/src/main/res/values"

  cat > "core-ui/build.gradle.kts" << EOF
plugins {
    alias(libs.plugins.android.library)
    alias(libs.plugins.kotlin.compose)
    alias(libs.plugins.ktlint)
}

android {
    namespace = "$PKG.core.ui"
    compileSdk {
        version =
            release(37) {
                minorApiLevel = 0
            }
    }

    defaultConfig {
        minSdk = 24
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
    buildFeatures {
        compose = true
    }
}

dependencies {
    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.compose.material3)
    implementation(libs.androidx.compose.ui)
    implementation(libs.androidx.compose.ui.graphics)
    implementation(libs.androidx.compose.ui.tooling.preview)
    debugImplementation(libs.androidx.compose.ui.tooling)
}
EOF

  # A vanilla Android Studio Compose template already generates ui/theme/ inside
  # the app module — migrate it into :core-ui rather than leaving a duplicate.
  # (Package declarations are untouched: modules are a Gradle/build boundary,
  # not a package-naming one, so nothing importing these classes has to change.)
  if [ -d "$BASE_PKG/ui/theme" ]; then
    for THEME_KT in "$BASE_PKG/ui/theme"/*.kt; do
      [ -f "$THEME_KT" ] || continue
      mv "$THEME_KT" "core-ui/src/main/java/$NEW_PATH/ui/theme/"
    done
    rmdir "$BASE_PKG/ui/theme" "$BASE_PKG/ui" 2>/dev/null || true
    echo "  moved: $BASE_PKG/ui/theme -> core-ui/src/main/java/$NEW_PATH/ui/theme"
  fi

  echo "/build" > "core-ui/.gitignore"
  echo "  created: :core-ui module"
fi

if [ ! -f "core-utils/build.gradle.kts" ]; then
  mkdir -p "core-utils"
  cat > "core-utils/build.gradle.kts" << EOF
// Empty by design — a home for cross-feature helpers (formatting, validation,
// extension functions) that don't belong to any single feature and don't need
// Compose/Hilt/network deps. Add dependencies here only when real code needs them.
plugins {
    alias(libs.plugins.android.library)
    alias(libs.plugins.ktlint)
}

android {
    namespace = "$PKG.core.utils"
    compileSdk {
        version =
            release(37) {
                minorApiLevel = 0
            }
    }

    defaultConfig {
        minSdk = 24
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
}

dependencies {
    implementation(libs.androidx.core.ktx)
}
EOF
  echo "/build" > "core-utils/.gitignore"
  echo "  created: :core-utils module"
fi

if [ ! -f "core-network/build.gradle.kts" ]; then
  mkdir -p "core-network/src/main/java/$NEW_PATH/core/di"
  mkdir -p "core-network/src/main/java/$NEW_PATH/core/network"

  cat > "core-network/build.gradle.kts" << EOF
plugins {
    alias(libs.plugins.android.library)
    alias(libs.plugins.ksp)
    alias(libs.plugins.hilt.android)
    alias(libs.plugins.ktlint)
}

android {
    namespace = "$PKG.core.network"
    compileSdk {
        version =
            release(37) {
                minorApiLevel = 0
            }
    }

    defaultConfig {
        minSdk = 24
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
    buildFeatures {
        buildConfig = true
    }
}

dependencies {
    implementation(libs.hilt.android)
    ksp(libs.hilt.compiler)

    // api, not implementation: feature modules build Retrofit services
    // (e.g. \`retrofit.create(FooApiService::class.java)\`) directly against
    // the Retrofit instance this module provides, so they need these types
    // on their own compile classpath too.
    api(libs.retrofit)
    api(libs.retrofit.converter.gson)
    api(libs.okhttp)
    implementation(libs.okhttp.logging.interceptor)
}
EOF
  echo "/build" > "core-network/.gitignore"
  echo "  created: :core-network module"
fi

if [ ! -f "auth/build.gradle.kts" ]; then
  mkdir -p "auth/src/main/java/$NEW_PATH/auth/domain" "auth/src/main/java/$NEW_PATH/auth/data" "auth/src/main/java/$NEW_PATH/auth/presentation"
  cat > "auth/build.gradle.kts" << EOF
plugins {
    alias(libs.plugins.android.library)
    alias(libs.plugins.kotlin.compose)
    alias(libs.plugins.ksp)
    alias(libs.plugins.hilt.android)
    alias(libs.plugins.ktlint)
}

android {
    namespace = "$PKG.auth"
    compileSdk {
        version =
            release(37) {
                minorApiLevel = 0
            }
    }

    defaultConfig {
        minSdk = 24
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
    buildFeatures {
        compose = true
    }
}

dependencies {
    implementation(project(":core-ui"))
    implementation(project(":core-network"))
    implementation(project(":core-utils"))

    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.compose.material3)
    implementation(libs.androidx.compose.ui)
    implementation(libs.androidx.compose.ui.tooling.preview)
    implementation(libs.androidx.lifecycle.viewmodel.compose)
    implementation(libs.androidx.lifecycle.runtime.compose)
    debugImplementation(libs.androidx.compose.ui.tooling)

    implementation(libs.hilt.android)
    ksp(libs.hilt.compiler)

    implementation(libs.kotlinx.coroutines.android)
}
EOF

  cat > "auth/README.md" << 'EOF'
# :auth

Empty by design. This module is a wired, ready-to-use Gradle boundary for the
auth feature (login, signup, session) — it already depends on `:core-ui`,
`:core-network`, and `:core-utils`, and has Compose + Hilt configured.

No login/signup screens exist yet — there's no backend or session model to
build them against. When you add real auth logic, follow the standard
feature-first MVI structure from `docs/ai/architecture.md`:

```
src/main/java/<package>/auth/
  domain/          # models, repository interfaces, use cases
  data/            # repository impls, DTOs, remote/local data sources
  presentation/    # AuthUiState, AuthUiEvent, AuthViewModel, Screen/Route
```
EOF
  echo "/build" > "auth/.gitignore"
  echo "  created: :auth module"
fi

if ! grep -q 'project(":core-ui")' "$APP_GRADLE" 2>/dev/null; then
  insert_after "$APP_GRADLE" 'dependencies {' '    implementation(project(":core-ui"))
    implementation(project(":core-utils"))
    implementation(project(":core-network"))
    implementation(project(":auth"))'
  echo "  wired: :app -> core-ui, core-utils, core-network, auth"
fi

# ------------------------------------------------------------------------------
# 3. AI meta-files — written only if missing, so custom edits are never clobbered
# ------------------------------------------------------------------------------

echo "Writing AI meta-files (skipping any that already exist)..."

if [ ! -f "CLAUDE.md" ]; then
cat << 'EOF' > CLAUDE.md
# AI Agent Instructions

You are an expert Android Kotlin Developer. Before generating or modifying any code, you MUST read and strictly adhere to the standards defined in the following meta-files:

1. Architecture: Read `/docs/ai/architecture.md`
2. Compose Rules: Read `/docs/ai/compose_rules.md`
3. UI Synthesis: Read `/docs/ai/ui_synthesis_rules.md`

**Core Tech Stack:** Kotlin, Jetpack Compose, Hilt, Coroutines/StateFlow, Retrofit.

**Verify by building.** After generating or modifying any Kotlin/Gradle file, run `./gradlew :app:assembleDebug` (or the specific module/test task affected) before considering the task done. A change that "looks right" but hasn't been compiled is not verified.
EOF
  echo "  wrote: CLAUDE.md"
else
  echo "  skip (exists): CLAUDE.md"
fi

if [ ! -f "docs/ai/architecture.md" ]; then
cat << 'EOF' > docs/ai/architecture.md
# Architecture & Layer Rules

Strict Feature-First Clean Architecture combined with MVI on the presentation layer. Every feature lives inside its own package under `features/[feature_name]/`.

**UI is 100% Jetpack Compose.** No `res/layout/` XML, no `View`/`Fragment`-based screens, ever — every screen, dialog, and component is a Composable.

### Request/state flow (MVI, one feature)

```
┌──────────────────────────────┐
│         Composable UI        │
└──────────────┬───────────────┘
               │ UiEvent
               ▼
┌──────────────────────────────┐
│          ViewModel           │
│  StateFlow<UiState>          │
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────┐
│           UseCase            │
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────┐
│         Repository           │
└───────┬───────────────┬──────┘
        │               │
        ▼               ▼
Remote Data       Local Data
        │               │
        └───────┬───────┘
                ▼
          Domain Models
```

`StateFlow<UiState>` flows back up from the ViewModel to the Composable on every state change — that return arrow is omitted above since it's implicit in "the ViewModel exposes it and the Composable collects it," not a second call path. "Local Data" is aspirational until a feature actually adds Room or a DataStore — nothing here does yet.

### Module layout

This is a Gradle multi-module project, not just a package convention:

```
Project
│
├── :app
│    └── features/
│
├── :core-ui
│
├── :core-network
│
├── :core-utils
│
└── :auth
```

- **`:app`** — entry points (`App.kt`, `MainActivity.kt`) plus every feature generated by `scripts/new_feature.sh` under `features/<name>/`. Depends on all four modules below.
- **`:core-ui`** — theme (`ui/theme/`) and shared widgets (`shared_widgets/`). Every screen depends on this.
- **`:core-network`** — the Hilt-provided `OkHttpClient`/`Retrofit` instance and `NetworkConfig.BASE_URL`.
- **`:core-utils`** — empty by design, a home for cross-feature helpers that don't belong to any single feature.
- **`:auth`** — empty by design, a wired Gradle boundary (Compose + Hilt already configured) for the auth feature. No login/signup UI exists yet — see `auth/README.md`.

New features generated by `scripts/new_feature.sh` stay inside `:app`, exactly as documented below — they are **not** promoted to their own module. Only `:core-ui`/`:core-utils`/`:core-network`/`:auth` are separate modules; splitting out further feature modules is a deliberate, manual decision for a project that's grown enough to need it, not something the tooling does automatically.

### 1. Domain Layer (`domain/`)
- Pure business logic. NO framework dependencies (no Android, no Hilt, no Retrofit imports).
- Models, Repository Interfaces, and UseCases.

### 2. Data Layer (`data/`)
- Implements Domain interfaces.
- Retrofit API interfaces, Room DAOs, DTOs, and Mappers.

### 3. Presentation Layer (`presentation/`) — MVI

- **UI State**: one immutable `data class` representing everything the screen needs to render. Exposed as `val uiState: StateFlow<XxxUiState>`.
- **UI Event**: one sealed interface representing every action the user can take (`sealed interface XxxUiEvent { data object Load : XxxUiEvent }`). The ViewModel exposes a single `fun onEvent(event: XxxUiEvent)` entry point — Composables never call other ViewModel functions directly, they only dispatch events. This is what makes the pattern MVI rather than plain MVVM: one channel in, one state stream out.
- **Screens**: Compose UI functions. A `Route` collects `uiState` and passes the event dispatcher down (usually as small lambdas like `onRetry = { viewModel.onEvent(XxxUiEvent.Load) }`); the `Screen` itself stays stateless and preview-friendly — it never touches the ViewModel directly.

**One-time effects (navigation, snackbars, toasts) are not part of `UiState`** — a `UiState` field is re-read on every recomposition/rotation, so a one-shot event stored there would replay itself. When a feature needs one, add a `SharedFlow` in the ViewModel and expose it as a named `UiEffect`:

```kotlin
sealed interface XxxUiEffect {
    data object NavigateBack : XxxUiEffect
    data class ShowSnackbar(val message: String) : XxxUiEffect
}

private val _effects = MutableSharedFlow<XxxUiEffect>()
val effects: SharedFlow<XxxUiEffect> = _effects.asSharedFlow()

// inside onEvent's handling, when something one-time needs to happen:
viewModelScope.launch { _effects.emit(XxxUiEffect.ShowSnackbar("Saved")) }
```

The `Route` collects `effects` with `LaunchedEffect`/`collectAsStateWithLifecycle`-style collection and acts on it once. `scripts/new_feature.sh` does **not** generate this channel by default — the base generated feature (load one thing, no navigation) has nothing to emit, and an unused `SharedFlow` is dead code. Add it by hand, following this pattern, the first time a feature actually needs a one-time effect.

EOF
  echo "  wrote: docs/ai/architecture.md"
else
  echo "  skip (exists): docs/ai/architecture.md"
fi

if [ ! -f "docs/ai/compose_rules.md" ]; then
cat << 'EOF' > docs/ai/compose_rules.md
# Jetpack Compose Design Rules

1. **State Hoisting:** UIs must be stateless where possible. Hoist business logic to the ViewModel.
2. **ViewModel State:** Use `StateFlow` (e.g., `val uiState: StateFlow<MyUiState> = _uiState.asStateFlow()`).
3. **Collection:** Always collect state using `collectAsStateWithLifecycle()`.
4. **Previews:** Every Composable must have a `@Preview` function using mock data.
5. **No Hardcoded Text:** NEVER inline a literal user-facing string in a Composable. Put it in `res/values/strings.xml` and reference it via `stringResource(R.string.name)` — this is what makes the app translatable later without touching UI code. (Dynamic data being *displayed* — a name, a price, an error message coming from the backend — isn't "hardcoded text" and doesn't need a string resource; this rule is about copy the app itself authors: labels, button text, titles, placeholders.)
6. **Accessibility:** Every `Icon`/`Image` needs a `contentDescription` — a real one (ideally from `stringResource`) if it conveys meaning, or explicit `contentDescription = null` if it's purely decorative and an adjacent text label already says the same thing. Never leave it as a guess or omit the parameter.
7. **MVI, not direct ViewModel calls:** A Composable never calls a ViewModel function directly (no `viewModel.load()`, `viewModel.refresh()`, etc.). It takes a plain lambda parameter (e.g. `onRetry: () -> Unit`, `onSubmit: (String) -> Unit`) and the caller wires that lambda to `viewModel.onEvent(SomeUiEvent.X)` — one sealed `UiEvent` in, one `StateFlow<UiState>` out, per feature. This applies to buttons, form submits, retry actions, and any other user-triggered interaction — see `docs/ai/architecture.md` for the full pattern.
EOF
  echo "  wrote: docs/ai/compose_rules.md"
else
  echo "  skip (exists): docs/ai/compose_rules.md"
fi

if [ ! -f "docs/ai/ui_synthesis_rules.md" ]; then
cat << 'EOF' > docs/ai/ui_synthesis_rules.md
# UI Synthesis & Copying Rules

When building UI from images, screenshots, or HTML:
1. **No Hardcoding:** NEVER generate hardcoded HEX colors or font sizes.
2. **Theme Mapping:** Map colors to `MaterialTheme.colorScheme` and typography to `MaterialTheme.typography`.
3. **Components:** Extract repeatable elements (buttons, cards) into small, stateless Composable functions.
EOF
  echo "  wrote: docs/ai/ui_synthesis_rules.md"
else
  echo "  skip (exists): docs/ai/ui_synthesis_rules.md"
fi

if [ ! -f "docs/PROJECT_MAP.md" ]; then
cat << 'EOF' > docs/PROJECT_MAP.md
# Project Map

Quick orientation for the files that *aren't* covered by the feature-first naming
convention. Anything under `features/<name>/` is already self-explanatory from
`docs/ai/architecture.md` (`domain/model`, `domain/repository`, `domain/usecase`,
`data/remote`, `data/repository`, `presentation`) — no need to look those up here.
This file is only for everything else.

## Modules

Gradle modules, not just packages — each has its own `build.gradle.kts`.

| Module | Purpose |
|---|---|
| `:app` | Entry points (`App.kt`, `MainActivity.kt`) + every feature generated by `scripts/new_feature.sh` (`features/<name>/`). Depends on all four modules below. |
| `:core-ui` | Theme (`ui/theme/`) + shared widgets (`shared_widgets/`). Every screen in `:app` or `:auth` depends on this. |
| `:core-network` | Hilt-provided `OkHttpClient`/`Retrofit` (`core/di/NetworkModule.kt`) + `core/network/NetworkConfig.kt`'s `BASE_URL`. Exposes Retrofit/OkHttp as `api`, so feature modules get those types transitively. |
| `:core-utils` | Empty by design — a home for cross-feature helpers (formatting, validation, extensions) that don't belong to any single feature. |
| `:auth` | Empty by design — a wired Gradle boundary (Compose + Hilt configured, depends on the three modules above) for the auth feature. No login/signup UI exists yet since there's no backend or session model to build it against — see `auth/README.md`. |

Package names are unchanged by the module split — a class's package (e.g.
`<base package>.shared_widgets`) tells you nothing about which module it's
physically in; use this table for that.

## Gradle configuration (project root)

| File | Purpose |
|---|---|
| `settings.gradle.kts` | `include(":app", ":core-ui", ":core-utils", ":core-network", ":auth")` — the five modules above. |
| `build.gradle.kts` (root) | Declares every plugin used anywhere in the project (`apply false`) so each module can `alias()` it without redeclaring the version. |
| `gradle/libs.versions.toml` | **The Version Catalog.** Every dependency and plugin — group, artifact, version — for all five modules, declared once here and referenced as `libs.androidx.core.ktx`, `libs.plugins.hilt.android`, etc. in each module's `build.gradle.kts`. This is standard Android Studio scaffolding (default since 2023), not something added on top — if a `build.gradle.kts` looks like it's missing a version number, it's here instead. |
| `app/build.gradle.kts`, `core-ui/build.gradle.kts`, `core-network/build.gradle.kts`, `core-utils/build.gradle.kts`, `auth/build.gradle.kts` | Per-module Gradle config — plugins, `namespace`, dependencies (via the catalog above). Only `:app` has `applicationId`/`versionCode`/`versionName`; the other four are library modules. |
| `app/.gitignore`, `core-ui/.gitignore`, `core-network/.gitignore`, `core-utils/.gitignore`, `auth/.gitignore` | Each is just `/build` — every module ignores its own build output; there's no single top-level `/build` entry that covers all of them. |
| `local.properties` | SDK path — machine-specific, gitignored, not part of the template (every dev's Android Studio writes its own). |

## App entry points (`:app`)

| File | Purpose |
|---|---|
| `<base package>/App.kt` (this repo's own copy predates this convention and is named `AndroidAISkeletonApp.kt` instead) | `@HiltAndroidApp` — the Application class, root of the Hilt DI graph. |
| `<base package>/MainActivity.kt` | `@AndroidEntryPoint` host Activity. Any Composable using plain `viewModel()` (not `hiltViewModel()`) has to be shown from an `@AndroidEntryPoint` host — this is that host. |

## Core network (`:core-network`)

| File | Purpose |
|---|---|
| `core/di/NetworkModule.kt` | Hilt `@Module` providing the singleton `OkHttpClient` + `Retrofit` instance every generated feature's `*ApiModule.kt` builds on. |
| `core/network/NetworkConfig.kt` | Holds `BASE_URL` — the one place to point the whole app at a real API. |

## Theme (`:core-ui` — single source of truth for styling, see `docs/ai/ui_synthesis_rules.md`)

| File | Purpose |
|---|---|
| `ui/theme/Color.kt` | Color palette. |
| `ui/theme/Theme.kt` | The `@Composable` theme wrapper (e.g. `AndroidAISkeletonTheme` in this repo). `scripts/new_feature.sh` and the `ui-from-image` skill auto-detect whatever it's actually named in your project — never hardcode this name. |
| `ui/theme/Type.kt` | Typography scale. |
| `ui/theme/ThemeConfig.kt` | One value (`ThemeConfig.mode`) controlling whether the app follows the system light/dark setting or supports only one. See `README.md` for the three options. |

## Shared widgets (`:core-ui`)

| File | Purpose |
|---|---|
| `shared_widgets/LoadingIndicator.kt` | A centered `CircularProgressIndicator` — `scripts/new_feature.sh`'s generated `Screen.kt` uses this for its loading state instead of an inline spinner. |
| `shared_widgets/ErrorView.kt` | A centered error message. Used by generated `Screen.kt`s for their error state. |
| `shared_widgets/EmptyState.kt` | A centered "nothing here" message, for a feature's empty-data state. Not auto-wired into generated screens (there's no single generic "empty" condition to detect) — use it directly when a feature needs one. |

## Tooling (project root)

| File | Purpose |
|---|---|
| `init_skeleton.sh` | Single-file bootstrapper — see `README.md` / `ONBOARDING.md`. |
| `CLAUDE.md` | Anchor file, auto-loaded every Claude Code session — tech stack summary + pointers to `docs/ai/*.md`. |
| `auth/README.md` | Explains why `:auth` has no source files yet and the `domain`/`data`/`presentation` shape to follow when it gets real login/session logic. |
| `scripts/new_feature.sh` | Feature scaffold generator. |
| `scripts/check_embedded_sync.sh` | Verifies `init_skeleton.sh`'s embedded copies match their standalone files — run this after editing `new_feature.sh` or any `SKILL.md`, before shipping. |
| `scripts/check_hardcoded_colors.sh` | Flags a `Color(0x...)` hex literal anywhere outside `ui/theme/` — colors belong in `Color.kt`, referenced via `MaterialTheme.colorScheme`, not scattered one-off across screens/components. |
| `.githooks/pre-commit` | Runs the sync check and the hardcoded-color check above, plus `ktlintCheck` and the test suite if any `.kt`/`.kts` file is staged — blocks the commit on any failure. |
| `.claude/skills/new-feature/`, `.claude/skills/ui-from-image/`, `.claude/skills/translate/`, `.claude/skills/status/` | The four slash-command skills. |
| `docs/ai/*.md` | The architecture/Compose/UI rules the AI reads before writing code. |
| `TODO.md` | Auto-appended by `new_feature.sh` on every generated feature — manual follow-ups (wire navigation, set the real endpoint). Created on first use; won't exist in a project that hasn't scaffolded a feature yet. |
| `.editorconfig` | Disables three ktlint standard rules that would otherwise fight this project's real conventions: `package-name` (this repo's package has an underscore), `function-naming` (Composables are deliberately PascalCase), and `annotation` (Hilt's `@Inject constructor` idiom). Everything else in ktlint's default rule set stays on. |

## Everything else

If it's under `features/<name>/`, the convention in `docs/ai/architecture.md` tells
you where it lives — that's the point of the convention: predictable location
without needing a map entry for every file.

EOF
  echo "  wrote: docs/PROJECT_MAP.md"
else
  echo "  skip (exists): docs/PROJECT_MAP.md"
fi

# ------------------------------------------------------------------------------
# 4. Feature scaffold generator + Claude Code skills — written only if missing.
#
#    These are embedded copies so this ONE file is all a developer needs to
#    bootstrap a brand-new project (no separate clone/copy step). If
#    scripts/new_feature.sh or any SKILL.md is changed in the canonical
#    skeleton repo, update the embedded blocks below to match, or fresh
#    projects will keep getting the old version.
# ------------------------------------------------------------------------------

echo "Writing scaffold generator + Claude Code skills (skipping any that already exist)..."

mkdir -p scripts
mkdir -p .claude/skills/new-feature
mkdir -p .claude/skills/ui-from-image
mkdir -p .claude/skills/translate
mkdir -p .claude/skills/status

if [ ! -f "scripts/new_feature.sh" ]; then
cat << 'NEW_FEATURE_SCRIPT_EOF' > scripts/new_feature.sh
#!/bin/bash
# Deterministic feature scaffold generator. No LLM tokens spent on structure/boilerplate.
#
# Usage:
#   ./scripts/new_feature.sh <feature_name> ["field:Type,field:Type,..."]
#
# Example:
#   ./scripts/new_feature.sh user_settings "email:String,notificationsEnabled:Boolean"
#
# Generates the standard data/domain/presentation layers under
# features/<feature_name>/ per docs/ai/architecture.md and docs/ai/compose_rules.md,
# wired to the project's real Hilt + Retrofit + StateFlow stack.

set -euo pipefail

if [ $# -lt 1 ]; then
  echo "Usage: $0 <feature_name> [\"field:Type,field:Type,...\"]"
  exit 1
fi

RAW_NAME="$1"
FIELDS_RAW="${2:-id:String,title:String}"

# --- Name conversions -------------------------------------------------------

# package-safe snake_case: lowercase, spaces/hyphens -> underscores
PKG_NAME=$(echo "$RAW_NAME" | tr '[:upper:] -' '[:lower:]__' | tr -s '_')

# PascalCase class prefix, e.g. user_settings -> UserSettings
CLASS_PREFIX=$(echo "$PKG_NAME" | awk -F'_' '{ for (i=1; i<=NF; i++) printf "%s%s", toupper(substr($i,1,1)), substr($i,2) }')

# camelCase variable name, e.g. UserSettings -> userSettings
VAR_NAME="$(echo "${CLASS_PREFIX:0:1}" | tr '[:upper:]' '[:lower:]')${CLASS_PREFIX:1}"

# --- Auto-detect the app's real package + theme name ------------------------
# (so this script keeps working after init_skeleton.sh renames the package —
# nothing here should be hardcoded to this template's original package name)

APP_GRADLE="app/build.gradle.kts"
PROJECT_PKG=$(grep -oE 'namespace = "[^"]+"' "$APP_GRADLE" | head -1 | sed -E 's/namespace = "(.*)"/\1/')
if [ -z "$PROJECT_PKG" ]; then
  echo "Could not detect the app's package from $APP_GRADLE (expected a 'namespace = \"...\"' line)."
  exit 1
fi
PROJECT_PATH=$(echo "$PROJECT_PKG" | tr '.' '/')

THEME_FILE="core-ui/src/main/java/$PROJECT_PATH/ui/theme/Theme.kt"
THEME_FUN=$(grep -oE 'fun [A-Za-z0-9_]+Theme\(' "$THEME_FILE" 2>/dev/null | head -1 | sed -E 's/fun (.*)\(/\1/')
if [ -z "$THEME_FUN" ]; then
  echo "Could not detect the app's @Composable Theme wrapper under $THEME_FILE."
  exit 1
fi

BASE_PKG="app/src/main/java/$PROJECT_PATH"
FEATURE_DIR="$BASE_PKG/features/$PKG_NAME"
FEATURE_PKG="$PROJECT_PKG.features.$PKG_NAME"
TEST_FEATURE_DIR="app/src/test/java/$PROJECT_PATH/features/$PKG_NAME/presentation"

if [ -d "$FEATURE_DIR" ]; then
  echo "Feature '$PKG_NAME' already exists at $FEATURE_DIR — aborting so nothing gets overwritten."
  exit 1
fi

# --- Build the model field block from "name:Type,name:Type" ----------------
# Also builds a fake-value-per-field block for the generated test (Kotlin's
# TODO() is a Nothing, assignable to any type, so an unrecognized/custom type
# still compiles — it just fails loudly at test runtime instead of silently
# guessing a wrong default).

default_for_type() {
  case "$1" in
    *\?) echo "null" ;;
    String) echo '"test"' ;;
    Boolean) echo "true" ;;
    Int) echo "0" ;;
    Long) echo "0L" ;;
    Double) echo "0.0" ;;
    Float) echo "0f" ;;
    *) echo "TODO(\"provide a real $1 value for this test\")" ;;
  esac
}

MODEL_FIELDS=""
TEST_FIELD_DEFAULTS=""
IFS=',' read -ra FIELD_PAIRS <<< "$FIELDS_RAW"
for pair in "${FIELD_PAIRS[@]}"; do
  fname="${pair%%:*}"
  ftype="${pair##*:}"
  MODEL_FIELDS="${MODEL_FIELDS}    val ${fname}: ${ftype},\n"
  TEST_FIELD_DEFAULTS="${TEST_FIELD_DEFAULTS}            ${fname} = $(default_for_type "$ftype"),\n"
done
# Trailing comma on the last field is kept deliberately — ktlint's
# trailing-comma-on-declaration-site rule requires it for multi-line declarations.

echo "Scaffolding feature '$PKG_NAME' ($CLASS_PREFIX) under $FEATURE_DIR ..."

mkdir -p "$FEATURE_DIR/domain/model"
mkdir -p "$FEATURE_DIR/domain/repository"
mkdir -p "$FEATURE_DIR/domain/usecase"
mkdir -p "$FEATURE_DIR/data/remote"
mkdir -p "$FEATURE_DIR/data/repository"
mkdir -p "$FEATURE_DIR/presentation"
mkdir -p "$TEST_FEATURE_DIR"

# --- domain/model ------------------------------------------------------------

printf '%s' "package ${FEATURE_PKG}.domain.model

data class ${CLASS_PREFIX}(
$(printf "$MODEL_FIELDS")
)
" > "$FEATURE_DIR/domain/model/${CLASS_PREFIX}.kt"

# --- domain/repository --------------------------------------------------------

cat > "$FEATURE_DIR/domain/repository/${CLASS_PREFIX}Repository.kt" << EOF
package ${FEATURE_PKG}.domain.repository

import ${FEATURE_PKG}.domain.model.${CLASS_PREFIX}

interface ${CLASS_PREFIX}Repository {
    suspend fun get${CLASS_PREFIX}(): Result<${CLASS_PREFIX}>
}
EOF

# --- domain/usecase ------------------------------------------------------------

cat > "$FEATURE_DIR/domain/usecase/Get${CLASS_PREFIX}UseCase.kt" << EOF
package ${FEATURE_PKG}.domain.usecase

import ${FEATURE_PKG}.domain.model.${CLASS_PREFIX}
import ${FEATURE_PKG}.domain.repository.${CLASS_PREFIX}Repository
import javax.inject.Inject

class Get${CLASS_PREFIX}UseCase @Inject constructor(
    private val repository: ${CLASS_PREFIX}Repository,
) {
    suspend operator fun invoke(): Result<${CLASS_PREFIX}> = repository.get${CLASS_PREFIX}()
}
EOF

# --- data/remote ---------------------------------------------------------------

cat > "$FEATURE_DIR/data/remote/${CLASS_PREFIX}ApiService.kt" << EOF
package ${FEATURE_PKG}.data.remote

import ${FEATURE_PKG}.domain.model.${CLASS_PREFIX}
import retrofit2.http.GET

interface ${CLASS_PREFIX}ApiService {
    // TODO: point this at the real endpoint.
    @GET("${PKG_NAME}")
    suspend fun get${CLASS_PREFIX}(): ${CLASS_PREFIX}
}
EOF

# --- data/repository -------------------------------------------------------------

cat > "$FEATURE_DIR/data/repository/${CLASS_PREFIX}RepositoryImpl.kt" << EOF
package ${FEATURE_PKG}.data.repository

import ${FEATURE_PKG}.data.remote.${CLASS_PREFIX}ApiService
import ${FEATURE_PKG}.domain.model.${CLASS_PREFIX}
import ${FEATURE_PKG}.domain.repository.${CLASS_PREFIX}Repository
import javax.inject.Inject

class ${CLASS_PREFIX}RepositoryImpl @Inject constructor(
    private val apiService: ${CLASS_PREFIX}ApiService,
) : ${CLASS_PREFIX}Repository {
    override suspend fun get${CLASS_PREFIX}(): Result<${CLASS_PREFIX}> =
        runCatching {
            apiService.get${CLASS_PREFIX}()
        }
}
EOF

# --- presentation: UiState -----------------------------------------------------

cat > "$FEATURE_DIR/presentation/${CLASS_PREFIX}UiState.kt" << EOF
package ${FEATURE_PKG}.presentation

import ${FEATURE_PKG}.domain.model.${CLASS_PREFIX}

data class ${CLASS_PREFIX}UiState(
    val isLoading: Boolean = false,
    val ${VAR_NAME}: ${CLASS_PREFIX}? = null,
    val error: String? = null,
)

sealed interface ${CLASS_PREFIX}UiEvent {
    data object Load : ${CLASS_PREFIX}UiEvent
}
EOF

# --- presentation: ViewModel ----------------------------------------------------

cat > "$FEATURE_DIR/presentation/${CLASS_PREFIX}ViewModel.kt" << EOF
package ${FEATURE_PKG}.presentation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import ${FEATURE_PKG}.domain.usecase.Get${CLASS_PREFIX}UseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ${CLASS_PREFIX}ViewModel @Inject constructor(
    private val get${CLASS_PREFIX}UseCase: Get${CLASS_PREFIX}UseCase,
) : ViewModel() {
    private val _uiState = MutableStateFlow(${CLASS_PREFIX}UiState())
    val uiState: StateFlow<${CLASS_PREFIX}UiState> = _uiState.asStateFlow()

    init {
        onEvent(${CLASS_PREFIX}UiEvent.Load)
    }

    fun onEvent(event: ${CLASS_PREFIX}UiEvent) {
        when (event) {
            is ${CLASS_PREFIX}UiEvent.Load -> load()
        }
    }

    private fun load() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, error = null)
            get${CLASS_PREFIX}UseCase()
                .onSuccess { result ->
                    _uiState.value = _uiState.value.copy(isLoading = false, ${VAR_NAME} = result)
                }.onFailure { throwable ->
                    _uiState.value = _uiState.value.copy(isLoading = false, error = throwable.message)
                }
        }
    }
}
EOF

# --- test: ViewModel (real assertions, not a placeholder) ------------------------

cat > "$TEST_FEATURE_DIR/${CLASS_PREFIX}ViewModelTest.kt" << EOF
package ${FEATURE_PKG}.presentation

import ${FEATURE_PKG}.domain.model.${CLASS_PREFIX}
import ${FEATURE_PKG}.domain.repository.${CLASS_PREFIX}Repository
import ${FEATURE_PKG}.domain.usecase.Get${CLASS_PREFIX}UseCase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test

@OptIn(ExperimentalCoroutinesApi::class)
class ${CLASS_PREFIX}ViewModelTest {
    private val dispatcher = StandardTestDispatcher()

    @Before
    fun setUp() {
        Dispatchers.setMain(dispatcher)
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
    }

    private val fake${CLASS_PREFIX} =
        ${CLASS_PREFIX}(
$(printf "$TEST_FIELD_DEFAULTS")
        )

    // Takes a queue of results rather than one, so a test can make the fake repository
    // fail once and then succeed — e.g. to exercise a retry via onEvent(Load).
    private fun viewModel(results: List<Result<${CLASS_PREFIX}>>): ${CLASS_PREFIX}ViewModel {
        val queue = results.toMutableList()
        val repository =
            object : ${CLASS_PREFIX}Repository {
                override suspend fun get${CLASS_PREFIX}(): Result<${CLASS_PREFIX}> =
                    if (queue.size > 1) queue.removeAt(0) else queue.first()
            }
        return ${CLASS_PREFIX}ViewModel(Get${CLASS_PREFIX}UseCase(repository))
    }

    @Test
    fun \`successful load updates uiState with the result\`() =
        runTest {
            val vm = viewModel(listOf(Result.success(fake${CLASS_PREFIX})))
            dispatcher.scheduler.advanceUntilIdle()

            val state = vm.uiState.value
            assertFalse(state.isLoading)
            assertNull(state.error)
            assertEquals(fake${CLASS_PREFIX}, state.${VAR_NAME})
        }

    @Test
    fun \`failed load surfaces the error message\`() =
        runTest {
            val vm = viewModel(listOf(Result.failure(RuntimeException("boom"))))
            dispatcher.scheduler.advanceUntilIdle()

            val state = vm.uiState.value
            assertFalse(state.isLoading)
            assertEquals("boom", state.error)
            assertNull(state.${VAR_NAME})
        }

    @Test
    fun \`retrying via onEvent after a failure recovers\`() =
        runTest {
            val vm = viewModel(listOf(Result.failure(RuntimeException("boom")), Result.success(fake${CLASS_PREFIX})))
            dispatcher.scheduler.advanceUntilIdle()
            assertEquals("boom", vm.uiState.value.error)

            vm.onEvent(${CLASS_PREFIX}UiEvent.Load)
            dispatcher.scheduler.advanceUntilIdle()

            val state = vm.uiState.value
            assertFalse(state.isLoading)
            assertNull(state.error)
            assertEquals(fake${CLASS_PREFIX}, state.${VAR_NAME})
        }
}
EOF

# --- presentation: Screen --------------------------------------------------------

cat > "$FEATURE_DIR/presentation/${CLASS_PREFIX}Screen.kt" << EOF
package ${FEATURE_PKG}.presentation

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import ${PROJECT_PKG}.shared_widgets.ErrorView
import ${PROJECT_PKG}.shared_widgets.LoadingIndicator
import ${PROJECT_PKG}.ui.theme.${THEME_FUN}

// viewModel() resolves @HiltViewModel via the host Activity/Fragment's
// default factory, which requires that host to be @AndroidEntryPoint.
@Composable
fun ${CLASS_PREFIX}Route(
    modifier: Modifier = Modifier,
    viewModel: ${CLASS_PREFIX}ViewModel = viewModel(),
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    ${CLASS_PREFIX}Screen(
        uiState = uiState,
        onRetry = { viewModel.onEvent(${CLASS_PREFIX}UiEvent.Load) },
        modifier = modifier,
    )
}

@Composable
fun ${CLASS_PREFIX}Screen(
    uiState: ${CLASS_PREFIX}UiState,
    onRetry: () -> Unit = {},
    modifier: Modifier = Modifier,
) {
    when {
        uiState.isLoading -> LoadingIndicator(modifier = modifier)
        uiState.error != null -> ErrorView(message = uiState.error, onRetry = onRetry, modifier = modifier)
        uiState.${VAR_NAME} != null ->
            Column(
                modifier =
                    modifier
                        .fillMaxSize()
                        .padding(16.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Text(
                    text = uiState.${VAR_NAME}.toString(),
                    style = MaterialTheme.typography.bodyLarge,
                )
            }
    }
}

@Preview(showBackground = true)
@Composable
private fun ${CLASS_PREFIX}ScreenLoadingPreview() {
    ${THEME_FUN} {
        ${CLASS_PREFIX}Screen(uiState = ${CLASS_PREFIX}UiState(isLoading = true))
    }
}

@Preview(showBackground = true)
@Composable
private fun ${CLASS_PREFIX}ScreenErrorPreview() {
    ${THEME_FUN} {
        ${CLASS_PREFIX}Screen(uiState = ${CLASS_PREFIX}UiState(error = "Something went wrong"))
    }
}
EOF

# --- data/di: bind the repository interface to its implementation ----------------

cat > "$FEATURE_DIR/data/repository/${CLASS_PREFIX}Module.kt" << EOF
package ${FEATURE_PKG}.data.repository

import ${FEATURE_PKG}.domain.repository.${CLASS_PREFIX}Repository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent

@Module
@InstallIn(ViewModelComponent::class)
abstract class ${CLASS_PREFIX}Module {
    @Binds
    abstract fun bind${CLASS_PREFIX}Repository(impl: ${CLASS_PREFIX}RepositoryImpl): ${CLASS_PREFIX}Repository
}
EOF

cat > "$FEATURE_DIR/data/remote/${CLASS_PREFIX}ApiModule.kt" << EOF
package ${FEATURE_PKG}.data.remote

import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
object ${CLASS_PREFIX}ApiModule {
    @Provides
    @Singleton
    fun provide${CLASS_PREFIX}ApiService(retrofit: Retrofit): ${CLASS_PREFIX}ApiService = retrofit.create(${CLASS_PREFIX}ApiService::class.java)
}
EOF

echo "Done. Created:"
find "$FEATURE_DIR" -type f | sort
echo ""
echo "Next: wire ${CLASS_PREFIX}Route(...) into your navigation/MainActivity, and point"
echo "${CLASS_PREFIX}ApiService / NetworkConfig.BASE_URL at the real endpoint."

# --- record those two follow-ups so they survive across sessions ---------------

TODO_FILE="TODO.md"
if [ ! -f "$TODO_FILE" ]; then
  {
    echo "# TODO"
    echo ""
    echo "Auto-tracked follow-ups from scripts/new_feature.sh. Check items off as you finish them."
    echo ""
  } > "$TODO_FILE"
fi
{
  echo "- [ ] Wire \`${CLASS_PREFIX}Route()\` into navigation/MainActivity (features/${PKG_NAME})"
  echo "- [ ] Set the real endpoint for \`${CLASS_PREFIX}ApiService\` / confirm \`NetworkConfig.BASE_URL\` (features/${PKG_NAME})"
} >> "$TODO_FILE"
echo ""
echo "Recorded 2 follow-ups in $TODO_FILE."

# --- ktlint safety net -------------------------------------------------------
# The templates above are written to already be ktlint-clean for the common case,
# but a few of ktlint's wrapping rules (multiline-expression-wrapping, chain-method
# continuation) depend on exact line length, which varies with the feature/field
# names given to this script. Auto-formatting catches whatever that variance
# produces instead of shipping a feature that fails the project's own ktlintCheck.
if grep -q 'alias(libs.plugins.ktlint)' "$APP_GRADLE" 2>/dev/null && [ -x "./gradlew" ]; then
  if ./gradlew ktlintFormat --console=plain -q; then
    echo "Formatted with ktlint."
  else
    echo "Couldn't auto-format with ktlint — run './gradlew ktlintFormat' yourself before committing."
  fi
fi

NEW_FEATURE_SCRIPT_EOF
  chmod +x scripts/new_feature.sh
  echo "  wrote: scripts/new_feature.sh"
else
  echo "  skip (exists): scripts/new_feature.sh"
fi

if [ ! -f "scripts/check_embedded_sync.sh" ]; then
cat << 'CHECK_EMBEDDED_SYNC_EOF' > scripts/check_embedded_sync.sh
#!/bin/bash
# Drift check: init_skeleton.sh embeds copies of scripts/new_feature.sh and both
# SKILL.md files (so the single-file-copy bootstrap works without a separate
# clone/copy step). Editing the standalone file does NOT update the embedded
# copy — this script catches that silently going out of sync instead of relying
# on someone remembering the maintainer-note comment.
#
# Usage: ./scripts/check_embedded_sync.sh
# Exit code: 0 if everything matches, 1 if anything has drifted.

set -euo pipefail

INIT_SCRIPT="init_skeleton.sh"
FAILED=0

if [ ! -f "$INIT_SCRIPT" ]; then
  echo "Can't find $INIT_SCRIPT — run this from the project root."
  exit 1
fi

# Find every "cat << 'DELIM' > path" line in init_skeleton.sh and check that
# the embedded block between DELIM markers matches the real file at path.
while IFS= read -r line; do
  delim=$(echo "$line" | sed -E "s/.*cat << '([A-Z_]+)'.*/\1/")
  target=$(echo "$line" | sed -E 's/.*> (.*)$/\1/')

  if [ ! -f "$target" ]; then
    echo "DRIFT: $target is embedded in $INIT_SCRIPT but doesn't exist standalone."
    FAILED=1
    continue
  fi

  embedded=$(sed -n "/cat << '$delim' > $(echo "$target" | sed 's/[.\/]/\\&/g')/,/^${delim}\$/p" "$INIT_SCRIPT" | sed '1d;$d')
  actual=$(cat "$target")

  if [ "$embedded" = "$actual" ]; then
    echo "OK:    $target matches its embedded copy in $INIT_SCRIPT"
  else
    echo "DRIFT: $target does NOT match its embedded copy in $INIT_SCRIPT"
    echo "       -> edit the '$delim' block in $INIT_SCRIPT to match, then re-run this check."
    FAILED=1
  fi
done < <(grep -E "^cat << '[A-Z_]+' >" "$INIT_SCRIPT")

echo ""
if [ "$FAILED" -eq 0 ]; then
  echo "All embedded copies are in sync."
else
  echo "Sync check FAILED — see DRIFT lines above."
fi
exit "$FAILED"
CHECK_EMBEDDED_SYNC_EOF
  chmod +x scripts/check_embedded_sync.sh
  echo "  wrote: scripts/check_embedded_sync.sh"
else
  echo "  skip (exists): scripts/check_embedded_sync.sh"
fi

if [ ! -f "scripts/check_hardcoded_colors.sh" ]; then
cat << 'CHECK_HARDCODED_COLORS_EOF' > scripts/check_hardcoded_colors.sh
#!/bin/bash
# Flags hardcoded Color(0x...) hex literals in app code. Colors should be defined
# once under ui/theme/ (Color.kt's named vals, wired into Theme.kt's color scheme)
# and referenced via MaterialTheme.colorScheme from there on — otherwise every
# screen/component Claude (or a dev) generates can drift to its own one-off
# palette instead of staying on the app's real theme.
#
# Usage: ./scripts/check_hardcoded_colors.sh
# Exit code: 0 if clean, 1 if a hardcoded color literal is found outside ui/theme/.

set -euo pipefail

SEARCH_DIRS=(app/src/main/java core-ui/src/main/java core-utils/src/main/java core-network/src/main/java auth/src/main/java)
ALLOWED_DIR="ui/theme/"

EXISTING_DIRS=()
for dir in "${SEARCH_DIRS[@]}"; do
  [ -d "$dir" ] && EXISTING_DIRS+=("$dir")
done

if [ ${#EXISTING_DIRS[@]} -eq 0 ]; then
  echo "Can't find any of: ${SEARCH_DIRS[*]} — run this from the project root."
  exit 1
fi

MATCHES=$(grep -rn 'Color(0x' "${EXISTING_DIRS[@]}" --include="*.kt" | grep -v "/${ALLOWED_DIR}" || true)

if [ -n "$MATCHES" ]; then
  echo "Hardcoded color literal(s) found outside $ALLOWED_DIR:"
  echo ""
  echo "$MATCHES"
  echo ""
  echo "Add the color to $ALLOWED_DIR (Color.kt) and reference it via MaterialTheme.colorScheme"
  echo "instead of hardcoding a hex value in UI code."
  exit 1
fi

echo "No hardcoded color literals found outside $ALLOWED_DIR."
exit 0

CHECK_HARDCODED_COLORS_EOF
  chmod +x scripts/check_hardcoded_colors.sh
  echo "  wrote: scripts/check_hardcoded_colors.sh"
else
  echo "  skip (exists): scripts/check_hardcoded_colors.sh"
fi

if [ ! -f ".claude/skills/new-feature/SKILL.md" ]; then
cat << 'NEW_FEATURE_SKILL_EOF' > .claude/skills/new-feature/SKILL.md
---
name: new-feature
description: Scaffold a new feature (data/domain/presentation layers, Hilt ViewModel, Compose screen, Retrofit hookup) for this Android project from a minimal feature name + field list. Use this whenever the user asks to add, create, scaffold, or build a new feature/screen for this app, even if they only give a feature name and a couple of fields (e.g. "add a user_settings feature with email and notificationsEnabled"). Do NOT hand-write the data/domain/presentation boilerplate yourself when this skill applies — it exists specifically to generate that deterministically instead.
---

# New Feature Scaffolding

This project's whole point is minimal-command feature generation: the user gives a feature
name and maybe a few fields, and a complete, compiling feature comes out. The boilerplate
(Repository, UseCase, ViewModel, UiState, Screen, Hilt modules, Retrofit service) is generated
by a deterministic script — never hand-write it, that defeats the purpose and burns tokens on
output a shell script already produces for free.

## Steps

1. **Read the two small rule files** — `docs/ai/architecture.md` and `docs/ai/compose_rules.md`
   (about 10 lines total). That's all the context this task needs; don't read
   `docs/ai/ui_synthesis_rules.md` unless step 4 applies.

2. **Run the generator**:
   ```
   ./scripts/new_feature.sh <feature_name> "<field>:<Type>,<field>:<Type>,..."
   ```
   - `<feature_name>` becomes the package folder (snake_case) and the PascalCase class prefix,
     e.g. `user_settings` → `features/user_settings/`, class prefix `UserSettings`.
   - The field list is optional; it defaults to `id:String,title:String` if the user didn't give one.
   - This creates the full layer structure under the app's `features/<feature_name>/` package
     (wherever the project's real package lives — the script auto-detects it from
     `app/build.gradle.kts`, don't assume `com.example...`):
     domain model, repository interface, use case, Retrofit `ApiService` + its Hilt module,
     `RepositoryImpl` + its Hilt binding module, a `StateFlow`-based `@HiltViewModel`, a
     Compose `Screen` (+ `Route` wrapper) with two `@Preview` functions, and a real
     `<Feature>ViewModelTest.kt` (success + failure cases against a fake repository, not a
     placeholder) — plus two follow-up reminders appended to `TODO.md`.
   - The script refuses to run if the feature directory already exists, so it's safe to call directly.

3. **Fill in the one real placeholder.** The generated `<Feature>ApiService.kt` has a guessed
   endpoint path (`@GET("<feature_name>")`). If the user gave a real endpoint, update that
   annotation. Otherwise leave the TODO and just tell the user it's still a placeholder, along
   with the `:core-network` module's `NetworkConfig.kt` `BASE_URL` (shared across all features,
   only needs setting once).

4. **Only if the user asked for real UI** (specific fields displayed, a list vs. a detail view,
   a layout, a design reference) — edit `presentation/<Feature>Screen.kt` to build it. Nothing
   else the script generated should need touching for this. Follow `compose_rules.md` (stateless,
   hoisted composables) and, if a screenshot/design was given, `ui_synthesis_rules.md` (map colors/
   type to `MaterialTheme`, no hardcoded hex/sizes). Update the two `@Preview` functions with mock
   data that reflects the real UI instead of the generic placeholder text.

5. **Tell the user what's left**, briefly: wire `<Feature>Route()` into `MainActivity` (or the
   navigation graph, if one exists) and point the endpoint/`BASE_URL` at the real API once known.

## Why this shape

Splitting "generate structure" (free, deterministic, script) from "write the interesting part"
(the actual UI/business logic, which needs a model) is the whole efficiency gain here — every
feature should cost tokens roughly proportional to how custom its UI/logic actually is, not to
how much Kotlin boilerplate Clean Architecture requires.

NEW_FEATURE_SKILL_EOF
  echo "  wrote: .claude/skills/new-feature/SKILL.md"
else
  echo "  skip (exists): .claude/skills/new-feature/SKILL.md"
fi

if [ ! -f ".claude/skills/ui-from-image/SKILL.md" ]; then
cat << 'UI_FROM_IMAGE_SKILL_EOF' > .claude/skills/ui-from-image/SKILL.md
---
name: ui-from-image
description: Build Jetpack Compose UI for this Android project from an attached screenshot, mockup, or HTML reference — a full screen, a dialog/popup/bottom sheet/menu, or a standalone smaller component like a button, card, badge, or input field. Always reuses an existing `:core-ui` shared widget over building a new one, and always renders in this app's own MaterialTheme colors/typography, never the reference's literal palette. Use this whenever the user attaches or references an image/screenshot/design file and wants it turned into UI for this app, or asks to "build this screen", "copy this design", "match this mockup", "build this popup/dialog", "build this button/card", etc. Do NOT invent hex colors/font sizes or duplicate something already in shared_widgets/.
---

# UI Synthesis From an Image

Turn a visual reference into Compose UI that looks like it belongs in this app, not a
pixel-for-pixel copy with hardcoded values bolted on. Reading only the two rule files below is
enough context — don't re-derive these conventions from scratch each time.

## Steps

1. **Read `docs/ai/compose_rules.md` and `docs/ai/ui_synthesis_rules.md`** (both tiny). The
   non-negotiables: no hardcoded hex colors or raw sp/dp font sizes — map to
   `MaterialTheme.colorScheme` / `MaterialTheme.typography`; every composable gets an `@Preview`
   with mock data; UI is stateless and hoisted (no business logic inside the composable).

2. **Reuse `:core-ui`'s `shared_widgets/` before building anything new — check both up front and
   again for anything that emerges mid-build.** Run
   `ls core-ui/src/main/java/<package>/shared_widgets/`, break the reference into its pieces
   (heading, button, text field, link, card, badge, list row, loading/error/empty state...), and
   for each ask "does an existing widget already do this *by function*?" — a different label on
   the existing button widget, not a second button widget with slightly different styling. Only
   create a new `shared_widgets/` file for a piece nothing existing covers; put screen-specific
   layout and one-off decoration (background shapes, arrangement) inline in the screen itself.

3. **Render in this app's own theme, never the reference's literal colors.** Skim
   `ui/theme/Color.kt` and `Theme.kt` (`core-ui/src/main/java/<package>/ui/theme/` — that module,
   not `:app`, though the package name is unchanged; don't assume `com.example...`, use whatever
   `app/build.gradle.kts`'s `namespace` actually says) before mapping anything. A reference color
   tells you *which role* it plays (primary action, accent, error, surface...), not a value to
   reproduce — map to the closest `MaterialTheme.colorScheme` role even if it renders visibly
   differently (a purple-themed app keeps an orange reference's CTA as `colorScheme.primary`, not
   a new orange). Flag a poor role match explicitly so the user can decide whether to change the
   theme — never hardcode the reference's hex or add a new color to chase a visual match
   unprompted. Same for type: map to the `MaterialTheme.typography` scale, never a raw copied `sp`.

4. **Work out what kind of UI this actually is before deciding where it lives** — a design
   reference isn't automatically a full screen:
   - **A full screen** (occupies the whole content area, is something the user navigates to) →
     `features/<name>/presentation/<Name>Screen.kt` inside `:app`. Build inside an existing
     feature's `presentation/` if named, or create just the `presentation/` folder for a new one —
     don't run the full `new_feature.sh` scaffold for a pure UI build with no real data source yet.
     (The `new-feature` skill can generate those layers around it later if asked.)
     **Exception: a login/signup/session screen goes in `:auth`'s `presentation/`**
     (`auth/src/main/java/<package>/auth/presentation/<Name>Screen.kt`) — that module exists
     specifically as the auth feature's boundary (see `auth/README.md`). Same rule: UI only, no
     Repository/UseCase/ViewModel until there's a real backend.
   - **A dialog, popup, bottom sheet, dropdown/menu, snackbar, or other overlay** → a reusable
     component, not a screen — name it for what it is (`<Name>Dialog.kt`, `<Name>BottomSheet.kt`,
     matching the Compose API it's built on). `:core-ui`'s `shared_widgets/` if reusable across
     features, that feature's own `presentation/` in `:app` if tightly bound to its state. Never
     force it into a `*Screen.kt` file just because that's where screens go.
   - **A standalone smaller piece with no screen/overlay around it** — button, card, badge, input
     field, list row, chip → straight into `:core-ui`'s `shared_widgets/<Name>.kt`, parameterized
     (text/state/callbacks as parameters), no `Screen`/`Route` wrapper it didn't ask for.

5. **Write it stateless + hoisted**: a UI-state parameter and lambda callbacks (e.g. `onDismiss`,
   `onConfirm`), no ViewModel reference inside it. Add a thin `Route` wrapper only for a full
   screen that already has (or is about to get) a ViewModel — dialogs/popups almost never need one.

6. **Add `@Preview` functions** with mock data covering the states visible in the reference
   (loading/empty/error, shown/dismissed), per `compose_rules.md` — reusing
   `LoadingIndicator`/`ErrorView`/`EmptyState` from `shared_widgets/` rather than a new inline one.

7. **Tell the user**: what you built and where; what kind of component it is; which
   `shared_widgets/` pieces were reused vs. newly created (and why); and which colors/type map to
   which `MaterialTheme` roles, flagging any poor match rather than leaving it unmentioned.

UI_FROM_IMAGE_SKILL_EOF
  echo "  wrote: .claude/skills/ui-from-image/SKILL.md"
else
  echo "  skip (exists): .claude/skills/ui-from-image/SKILL.md"
fi

if [ ! -f ".claude/skills/translate/SKILL.md" ]; then
cat << 'TRANSLATE_SKILL_EOF' > .claude/skills/translate/SKILL.md
---
name: translate
description: Generate or update a localized strings.xml for this Android project from the English source (res/values/strings.xml), for a language the user names (e.g. "translate to Hindi", "add Spanish support", "localize this for French users"). Use this whenever the user asks to add a language, translate the app, or localize it. Do NOT hand-translate individual Composables one at a time when this applies — work from the single English strings.xml source of truth and produce a proper values-<lang>/strings.xml resource file.
---

# Generate a Localized strings.xml

Android's real localization mechanism is resource qualifiers (`values-hi/strings.xml`,
`values-es/strings.xml`, ...), not per-Composable translation. This only works at all if
`docs/ai/compose_rules.md` rule 5 (no hardcoded text) has actually been followed — if UI copy is
inlined in Composables instead of `res/values/strings.xml`, there's nothing here to translate.

## Steps

1. **Read every English source of truth, not just `:app`'s.** This is a multi-module project —
   `app/src/main/res/values/strings.xml` holds feature/screen copy, but `:core-ui` has its own
   `core-ui/src/main/res/values/strings.xml` (currently just the "Retry" button text `ErrorView`
   uses). Check both; a module only gets a `values/strings.xml` once something in it needs one, so
   don't assume `:core-ui`'s exists — `ls core-ui/src/main/res/values/` first. Treat whichever
   exist as the source, never edit them as part of this task.

2. **Work out the target resource folder** from what the user asked for:
   - Language only (most common — "Hindi", "Spanish") → the ISO 639-1 code: `values-hi`, `values-es`,
     `values-fr`, `values-de`, `values-ja`, `values-zh`, etc.
   - Language + region ("Mexican Spanish", "Brazilian Portuguese") → `values-<lang>-r<REGION>`
     (e.g. `values-es-rMX`, `values-pt-rBR`) — the older, more broadly-supported qualifier format.
   - If genuinely unsure which code the user means, ask rather than guess — a wrong locale
     qualifier means Android silently never serves the translation.

3. **Do this per module** — once for `app/src/main/res/values-<qualifier>/strings.xml` against
   `app`'s English source, and again for `core-ui/src/main/res/values-<qualifier>/strings.xml`
   against `core-ui`'s, if `core-ui` has an English `strings.xml` at all. They're independent
   resource sets; a string existing in one module's translation says nothing about the other's.
   For each target file:
   - **If it exists**: parse it, diff the `name` attributes against that module's English file, and
     translate *only the missing ones* — append them into the existing file. Never overwrite a
     string that's already translated there; someone may have hand-corrected it, and silently
     clobbering a human review is exactly the kind of silent-regression this project tries to avoid
     elsewhere (see `docs/PROJECT_MAP.md` / the drift-check philosophy). If you think an existing
     translation is wrong, say so and ask — don't just change it.
   - **If it doesn't exist**: create it fresh with every string from that module's English file
     translated.

4. **Translate carefully, not literally file-by-file**:
   - Keep every `name` attribute byte-for-byte identical to the English source — only the text
     content changes.
   - Preserve format specifiers exactly (`%1$s`, `%2$d`, `%s`) in the same relative order the
     target language needs them in — grammar order can differ between languages even when the
     placeholders are the same.
   - Preserve XML escaping (`\'`, `\"`, `&amp;`, etc.) — a raw unescaped apostrophe or quote in a
     translated string breaks the build.
   - If the project has `plurals.xml` or string-array resources, translate those the same way,
     respecting each language's own plural-category rules (some languages have more or fewer
     plural forms than English's one/other).
   - Leave `app_name` (and any other genuine brand/product name) untranslated unless the user
     explicitly asks for it to change — a product name usually stays the same across locales,
     and naively translating a proper noun tends to read as a mistake rather than a real name.

5. **Tell the user plainly**: which strings were added or left untouched, and that this is a
   solid first-pass translation, not a substitute for native-speaker review before shipping to
   real users in that language — flag anything genuinely ambiguous (a string whose meaning depends
   on context you don't have) rather than silently picking one interpretation.

## What this does not do

It doesn't change any Kotlin/Compose code, and it doesn't retroactively fix hardcoded strings —
if compose_rules.md rule 5 was already broken before this runs, point that out and offer to fix
the offending Composables first (extract to `strings.xml`, then translate), rather than silently
skipping content that was never externalized.

TRANSLATE_SKILL_EOF
  echo "  wrote: .claude/skills/translate/SKILL.md"
else
  echo "  skip (exists): .claude/skills/translate/SKILL.md"
fi

if [ ! -f ".claude/skills/status/SKILL.md" ]; then
cat << 'STATUS_SKILL_EOF' > .claude/skills/status/SKILL.md
---
name: status
description: Give a live snapshot of this project's current state — what features exist, what's still on the TODO list, and whether init_skeleton.sh's embedded copies are in sync. Use this whenever the user asks "what have we built", "what's left to do", "what features exist", "is everything in sync", or similar status/overview questions about this specific project. Do NOT answer these from memory or by guessing — always compute this live, since a stale answer is worse than no answer.
---

# Project Status

This is deliberately **computed fresh every time**, not read from a cached summary file —
a static "what have we built" doc goes stale the moment a feature is hand-edited or deleted,
and nothing would catch that drift. Live checks can't lie.

## Steps

1. **List what's actually built**: `ls features/` under the app's base package
   (`app/src/main/java/<package/path>/features/`, from `docs/PROJECT_MAP.md` if you need the
   exact path). This is the real inventory — not a summary of it.

2. **Check embedded-copy sync**: run `./scripts/check_embedded_sync.sh`. Report any `DRIFT`
   lines plainly — this is the one thing that silently breaks fresh-project bootstraps if
   ignored.

3. **Summarize `TODO.md`** if it exists (it won't in a project with no scaffolded features yet):
   count open items, group them by feature if there are several. Don't just dump the raw file —
   a short summary ("3 features have unwired routes, 2 still need real endpoints") is more useful
   than a wall of checkboxes.

4. **Report build health only if asked, not by default** — running `./gradlew assembleDebug` or
   `./gradlew test` is not free, so don't do it automatically as part of a quick status check.
   Mention it's available ("run `./gradlew test` for full confidence") rather than running it
   unprompted.

5. **Present it as a short summary**, not a wall of raw command output: feature count and names,
   sync status (one line), TODO summary (one line or a short list). If everything's clean, say so
   briefly rather than padding the answer.
STATUS_SKILL_EOF
  echo "  wrote: .claude/skills/status/SKILL.md"
else
  echo "  skip (exists): .claude/skills/status/SKILL.md"
fi

# ------------------------------------------------------------------------------
# 5. Git hook enforcing the embedded-copy drift check, if this is a git repo.
#    Shared via core.hooksPath (a tracked dir) rather than .git/hooks (untracked),
#    so every clone/copy that runs this script gets it, not just this machine.
# ------------------------------------------------------------------------------

if [ -d ".git" ]; then
  mkdir -p .githooks
  if [ ! -f ".githooks/pre-commit" ]; then
cat << 'PRE_COMMIT_HOOK_EOF' > .githooks/pre-commit
#!/bin/bash
# Pre-commit hook:
#   1. Blocks the commit if init_skeleton.sh's embedded copies have drifted
#      from their standalone files (scripts/new_feature.sh, all four SKILL.md
#      files, CLAUDE.md, docs/ai/*.md, docs/PROJECT_MAP.md).
#   2. If any Kotlin file is staged, blocks the commit on a hardcoded
#      Color(0x...) literal found outside ui/theme/ — colors belong in the
#      theme, not scattered one-off across screens/components.
#   3. If any Kotlin/Gradle file is staged, runs ktlintCheck (if wired) and the
#      unit test suite (which also compiles everything, main + test sources),
#      blocking the commit if either fails — "verify by building" (CLAUDE.md)
#      enforced, not just requested. Skipped for doc/script-only commits so
#      those stay fast.
#
# Shared via `git config core.hooksPath .githooks` (set automatically by
# init_skeleton.sh when a .git directory is present) — every dev who runs
# init_skeleton.sh on a git-initialized project gets this enforced, not just
# whoever remembers to run scripts/check_embedded_sync.sh or ./gradlew by hand.

if [ -f "scripts/check_embedded_sync.sh" ]; then
  bash scripts/check_embedded_sync.sh
  if [ $? -ne 0 ]; then
    echo ""
    echo "Commit blocked: init_skeleton.sh's embedded copies are out of sync."
    echo "Fix the DRIFT lines above (edit the matching block in init_skeleton.sh),"
    echo "then commit again."
    exit 1
  fi
fi

if git diff --cached --name-only | grep -qE '\.kt$'; then
  if [ -f "scripts/check_hardcoded_colors.sh" ]; then
    bash scripts/check_hardcoded_colors.sh
    if [ $? -ne 0 ]; then
      echo ""
      echo "Commit blocked: hardcoded color literal(s) found (see above)."
      echo "Move them into ui/theme/Color.kt, then commit again."
      exit 1
    fi
  fi
fi

if git diff --cached --name-only | grep -qE '\.(kt|kts)$'; then
  if [ -f "./gradlew" ]; then
    if grep -q 'alias(libs.plugins.ktlint)' "app/build.gradle.kts" 2>/dev/null; then
      echo "Kotlin/Gradle files staged — running ktlintCheck before commit..."
      ./gradlew ktlintCheck --console=plain
      if [ $? -ne 0 ]; then
        echo ""
        echo "Commit blocked: ktlint found style violations."
        echo "Run './gradlew ktlintFormat' to auto-fix, then commit again."
        exit 1
      fi
    fi

    echo "Kotlin/Gradle files staged — running the test suite before commit..."
    ./gradlew testDebugUnitTest --console=plain
    if [ $? -ne 0 ]; then
      echo ""
      echo "Commit blocked: the project doesn't compile or a test failed."
      echo "Fix the failure above, then commit again."
      exit 1
    fi
  fi
fi
PRE_COMMIT_HOOK_EOF
    chmod +x .githooks/pre-commit
    echo "  wrote: .githooks/pre-commit"
  else
    echo "  skip (exists): .githooks/pre-commit"
  fi
  git config core.hooksPath .githooks
  echo "  configured: git core.hooksPath -> .githooks"
fi

# ------------------------------------------------------------------------------
# 6. Configurable light/dark mode (ThemeConfig) — every app needs some answer to
#    this, and "SYSTEM vs LIGHT-only vs DARK-only" is a one-line decision, not a
#    dependency. Gated on ThemeConfig not already being wired into Theme.kt.
# ------------------------------------------------------------------------------

THEME_FILE_FOR_CONFIG="core-ui/src/main/java/$NEW_PATH/ui/theme/Theme.kt"

if [ -f "$THEME_FILE_FOR_CONFIG" ] && ! grep -q "ThemeConfig" "$THEME_FILE_FOR_CONFIG"; then
  if [ ! -f "core-ui/src/main/java/$NEW_PATH/ui/theme/ThemeConfig.kt" ]; then
    cat > "core-ui/src/main/java/$NEW_PATH/ui/theme/ThemeConfig.kt" << EOF
package $PKG.ui.theme

enum class ThemeMode { SYSTEM, LIGHT, DARK }

object ThemeConfig {
    // SYSTEM follows the device setting (default). Set LIGHT or DARK if this app only supports one mode.
    val mode: ThemeMode = ThemeMode.SYSTEM
}
EOF
    echo "  wrote: core-ui/src/main/java/$NEW_PATH/ui/theme/ThemeConfig.kt"
  fi

  if grep -q "darkTheme: Boolean = isSystemInDarkTheme()," "$THEME_FILE_FOR_CONFIG"; then
    replace_line "$THEME_FILE_FOR_CONFIG" "darkTheme: Boolean = isSystemInDarkTheme()," '    darkTheme: Boolean = when (ThemeConfig.mode) {
        ThemeMode.LIGHT -> false
        ThemeMode.DARK -> true
        ThemeMode.SYSTEM -> isSystemInDarkTheme()
    },'
    echo "  wired ThemeConfig into $THEME_FILE_FOR_CONFIG"
  else
    echo "  wrote ThemeConfig.kt, but $THEME_FILE_FOR_CONFIG doesn't match the expected"
    echo "  pattern — wire 'darkTheme: Boolean = when (ThemeConfig.mode) { ... }' in by hand."
  fi
elif [ -f "$THEME_FILE_FOR_CONFIG" ]; then
  echo "  skip (already wired): ThemeConfig in $THEME_FILE_FOR_CONFIG"
else
  echo "  skip: no $THEME_FILE_FOR_CONFIG found to wire ThemeConfig into."
fi

# ------------------------------------------------------------------------------
# 7. Gradle wiring: Hilt + KSP + Retrofit + OkHttp + Coroutines + viewmodel-compose
#    Gated on a single marker (the "hilt" version key) so a re-run is a clean no-op.
# ------------------------------------------------------------------------------

if grep -q '^hilt = ' "$TOML" 2>/dev/null; then
  echo "Gradle stack already wired — skipping."
else
  echo "Wiring Hilt + Retrofit + OkHttp + Coroutines into Gradle..."

  # NOTE: these versions were verified against Maven Central / the Gradle Plugin
  # Portal at the time this script was written. Bump them in gradle/libs.versions.toml
  # later if newer compatible releases exist — don't assume they're still latest.
  insert_after "$TOML" '[versions]' 'ksp = "2.3.10"
hilt = "2.60.1"
retrofit = "3.0.0"
okhttp = "5.4.0"
coroutines = "1.11.0"'

  insert_after "$TOML" '[libraries]' 'androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleRuntimeKtx" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycleRuntimeKtx" }
hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" }
hilt-compiler = { group = "com.google.dagger", name = "hilt-compiler", version.ref = "hilt" }
retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
retrofit-converter-gson = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "retrofit" }
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
okhttp-logging-interceptor = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" }
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" }'

  insert_after "$TOML" '[plugins]' 'ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
hilt-android = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }'

  insert_after "$ROOT_GRADLE" 'alias(libs.plugins.kotlin.compose) apply false' '    alias(libs.plugins.ksp) apply false
    alias(libs.plugins.hilt.android) apply false'

  insert_after "$APP_GRADLE" 'alias(libs.plugins.kotlin.compose)' '    alias(libs.plugins.ksp)
    alias(libs.plugins.hilt.android)'

  insert_after "$APP_GRADLE" 'implementation(libs.androidx.lifecycle.runtime.ktx)' '    implementation(libs.androidx.lifecycle.viewmodel.compose)
    implementation(libs.androidx.lifecycle.runtime.compose)

    implementation(libs.hilt.android)
    ksp(libs.hilt.compiler)

    implementation(libs.kotlinx.coroutines.android)'

  insert_after "$APP_GRADLE" 'testImplementation(libs.junit)' '    testImplementation(libs.kotlinx.coroutines.test)'

  insert_before "$MANIFEST" '<application' '    <uses-permission android:name="android.permission.INTERNET" />
'
  insert_after "$MANIFEST" '<application' '        android:name=".App"'

  cat > "$BASE_PKG/App.kt" << EOF
package $PKG

import android.app.Application
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class App : Application()
EOF

  cat > "core-network/src/main/java/$NEW_PATH/core/network/NetworkConfig.kt" << EOF
package $PKG.core.network

object NetworkConfig {
    // TODO: point this at the real API before shipping a feature that uses it.
    const val BASE_URL = "https://example.com/api/"
}
EOF

  cat > "core-network/src/main/java/$NEW_PATH/core/di/NetworkModule.kt" << EOF
package $PKG.core.di

import $PKG.core.network.BuildConfig
import $PKG.core.network.NetworkConfig
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
    @Provides
    @Singleton
    fun provideOkHttpClient(): OkHttpClient {
        val logging =
            HttpLoggingInterceptor().apply {
                level =
                    if (BuildConfig.DEBUG) {
                        HttpLoggingInterceptor.Level.BODY
                    } else {
                        HttpLoggingInterceptor.Level.NONE
                    }
            }
        return OkHttpClient
            .Builder()
            .addInterceptor(logging)
            .build()
    }

    @Provides
    @Singleton
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit =
        Retrofit
            .Builder()
            .baseUrl(NetworkConfig.BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
}
EOF

  MAIN_ACTIVITY=$(find "$BASE_PKG" -maxdepth 1 -name "MainActivity.kt")
  if [ -n "$MAIN_ACTIVITY" ] && ! grep -q "AndroidEntryPoint" "$MAIN_ACTIVITY"; then
    insert_after "$MAIN_ACTIVITY" "package $PKG" '
import dagger.hilt.android.AndroidEntryPoint'
    insert_before "$MAIN_ACTIVITY" "class MainActivity" '@AndroidEntryPoint'
  fi
fi

# ------------------------------------------------------------------------------
# 8. Shared loading/error/empty-state composables — new_feature.sh's generated
#    screens reference these instead of reinventing them inline each time.
#    Gated on detecting the app's Theme wrapper (same detection new_feature.sh
#    itself requires to run at all, so if this can't find it, neither can that).
# ------------------------------------------------------------------------------

SHARED_WIDGETS_DIR="core-ui/src/main/java/$NEW_PATH/shared_widgets"
THEME_FILE_FOR_WIDGETS="core-ui/src/main/java/$NEW_PATH/ui/theme/Theme.kt"
THEME_FUN_FOR_WIDGETS=$(grep -oE 'fun [A-Za-z0-9_]+Theme\(' "$THEME_FILE_FOR_WIDGETS" 2>/dev/null | head -1 | sed -E 's/fun (.*)\(/\1/')
CORE_UI_STRINGS_XML="core-ui/src/main/res/values/strings.xml"

if [ -n "$THEME_FUN_FOR_WIDGETS" ]; then
  mkdir -p "$SHARED_WIDGETS_DIR"
  mkdir -p "core-ui/src/main/res/values"

  if [ ! -f "$CORE_UI_STRINGS_XML" ]; then
    cat > "$CORE_UI_STRINGS_XML" << 'STRINGS_EOF'
<resources>
    <string name="retry">Retry</string>
</resources>
STRINGS_EOF
    echo "  wrote: $CORE_UI_STRINGS_XML (ErrorView's retry button)"
  elif ! grep -q 'name="retry"' "$CORE_UI_STRINGS_XML"; then
    insert_before "$CORE_UI_STRINGS_XML" '</resources>' '    <string name="retry">Retry</string>'
    echo "  added: retry string resource to $CORE_UI_STRINGS_XML (ErrorView's retry button)"
  fi

  if [ ! -f "$SHARED_WIDGETS_DIR/LoadingIndicator.kt" ]; then
    cat > "$SHARED_WIDGETS_DIR/LoadingIndicator.kt" << EOF
package $PKG.shared_widgets

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import $PKG.ui.theme.$THEME_FUN_FOR_WIDGETS

@Composable
fun LoadingIndicator(modifier: Modifier = Modifier) {
    Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        CircularProgressIndicator()
    }
}

@Preview(showBackground = true)
@Composable
private fun LoadingIndicatorPreview() {
    $THEME_FUN_FOR_WIDGETS {
        LoadingIndicator()
    }
}
EOF
    echo "  wrote: $SHARED_WIDGETS_DIR/LoadingIndicator.kt"
  else
    echo "  skip (exists): $SHARED_WIDGETS_DIR/LoadingIndicator.kt"
  fi

  if [ ! -f "$SHARED_WIDGETS_DIR/ErrorView.kt" ]; then
    cat > "$SHARED_WIDGETS_DIR/ErrorView.kt" << EOF
package $PKG.shared_widgets

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import $PKG.core.ui.R
import $PKG.ui.theme.$THEME_FUN_FOR_WIDGETS

@Composable
fun ErrorView(
    message: String,
    onRetry: (() -> Unit)? = null,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier =
            modifier
                .fillMaxSize()
                .padding(16.dp),
        contentAlignment = Alignment.Center,
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Text(text = message, style = MaterialTheme.typography.bodyLarge)
            if (onRetry != null) {
                TextButton(onClick = onRetry) {
                    Text(stringResource(R.string.retry))
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun ErrorViewPreview() {
    $THEME_FUN_FOR_WIDGETS {
        ErrorView(message = "Something went wrong", onRetry = {})
    }
}
EOF
    echo "  wrote: $SHARED_WIDGETS_DIR/ErrorView.kt"
  else
    echo "  skip (exists): $SHARED_WIDGETS_DIR/ErrorView.kt"
  fi

  if [ ! -f "$SHARED_WIDGETS_DIR/EmptyState.kt" ]; then
    cat > "$SHARED_WIDGETS_DIR/EmptyState.kt" << EOF
package $PKG.shared_widgets

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import $PKG.ui.theme.$THEME_FUN_FOR_WIDGETS

@Composable
fun EmptyState(
    message: String,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier =
            modifier
                .fillMaxSize()
                .padding(16.dp),
        contentAlignment = Alignment.Center,
    ) {
        Text(text = message, style = MaterialTheme.typography.bodyLarge)
    }
}

@Preview(showBackground = true)
@Composable
private fun EmptyStatePreview() {
    $THEME_FUN_FOR_WIDGETS {
        EmptyState(message = "Nothing here yet")
    }
}
EOF
    echo "  wrote: $SHARED_WIDGETS_DIR/EmptyState.kt"
  else
    echo "  skip (exists): $SHARED_WIDGETS_DIR/EmptyState.kt"
  fi
else
  echo "  skip: couldn't detect the app's Theme wrapper — add core-ui's shared_widgets/LoadingIndicator.kt,"
  echo "  ErrorView.kt, EmptyState.kt by hand if you want new_feature.sh's generated screens to"
  echo "  use them (its generated Screen.kt already imports and calls these three composables)."
fi

# ------------------------------------------------------------------------------
# 9. ktlint — automated Kotlin style enforcement, so style nits never cost a
#    review comment or a Claude turn. Gated on the "ktlint" version key so a
#    re-run is a clean no-op.
# ------------------------------------------------------------------------------

if grep -q '^ktlint = ' "$TOML" 2>/dev/null; then
  echo "ktlint already wired — skipping."
else
  echo "Wiring ktlint..."

  # NOTE: verified against the Gradle Plugin Portal at the time this script was
  # written. Bump it in gradle/libs.versions.toml later if a newer release exists.
  insert_after "$TOML" '[versions]' 'ktlint = "14.2.0"'
  insert_after "$TOML" '[plugins]' 'ktlint = { id = "org.jlleitschuh.gradle.ktlint", version.ref = "ktlint" }'

  insert_after "$ROOT_GRADLE" 'alias(libs.plugins.hilt.android) apply false' '    alias(libs.plugins.ktlint) apply false'
  insert_after "$APP_GRADLE" 'alias(libs.plugins.hilt.android)' '    alias(libs.plugins.ktlint)'

  if [ ! -f ".editorconfig" ]; then
cat << 'EDITORCONFIG_EOF' > .editorconfig
root = true

[*.{kt,kts}]
# com.example.android_ai_skeleton is this project's deliberate, established package name —
# not a code quality issue ktlint should block on.
ktlint_standard_package-name = disabled
# Jetpack Compose convention: @Composable functions are PascalCase (they act like widgets),
# which ktlint's standard function-naming rule doesn't recognize.
ktlint_standard_function-naming = disabled
# Hilt's idiomatic `class Foo @Inject constructor(...)` puts the annotation inline —
# ktlint's standard rule wants it (and @HiltViewModel etc.) on its own line, which
# turns every ViewModel/UseCase/Repository into a deeply indented pyramid for no
# real readability gain.
ktlint_standard_annotation = disabled
EDITORCONFIG_EOF
    echo "  wrote: .editorconfig"
  else
    echo "  skip (exists): .editorconfig"
  fi

  # Android Studio's own project template (ExampleUnitTest.kt / ExampleInstrumentedTest.kt)
  # ships a wildcard import that ktlint flags but can't auto-correct — fix it deterministically
  # rather than let the very first ktlintCheck fail on files nobody hand-wrote.
  for PLACEHOLDER_TEST in \
    "app/src/test/java/$NEW_PATH/ExampleUnitTest.kt" \
    "app/src/androidTest/java/$NEW_PATH/ExampleInstrumentedTest.kt"; do
    if [ -f "$PLACEHOLDER_TEST" ] && grep -q 'import org.junit.Assert.\*' "$PLACEHOLDER_TEST"; then
      replace_line "$PLACEHOLDER_TEST" 'import org.junit.Assert.*' 'import org.junit.Assert.assertEquals'
      echo "  fixed wildcard import in $PLACEHOLDER_TEST"
    fi
  done

  echo "  wired ktlint — auto-formatting existing files..."
  if [ -x "./gradlew" ] && ./gradlew ktlintFormat --console=plain -q; then
    echo "  ran './gradlew ktlintFormat' — main/test sources are now ktlint-clean."
  else
    echo "  couldn't run './gradlew ktlintFormat' automatically (no SDK configured yet?)."
    echo "  run it yourself once the project builds, then './gradlew ktlintCheck' to confirm."
  fi
fi

echo ""
echo "Done. Package: $PKG"
if [ "$RENAMED" = true ]; then
  echo "Renamed an existing package — if this project has been built before, run"
  echo "'./gradlew clean' once before your next build (stale incremental/KSP state"
  echo "from the old package name can otherwise cause a spurious compile error)."
fi
echo "Initialization complete! Your project is now AI-ready."
