"""Content templates for APX-scaffolded apps.

Separated from ``apx_bridge`` to keep the bridge module under the 300-line limit.
These are plain string constants — no runtime logic.
"""

from __future__ import annotations

import logging
from pathlib import Path

from exokit.core.models import ScaffoldContext

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
# App CLAUDE.md content
# ---------------------------------------------------------------------------

APP_CLAUDE_MD = """\
# {app_name} — App-Level CLAUDE.md

## Architecture

This app uses **APX** (Databricks App Framework) with a **3-layer backend** overlay:

```
src/{app_slug}/
├── backend/
│   ├── app.py              # APX FastAPI app factory (DO NOT MODIFY core/)
│   ├── core/               # APX internals — config, dependencies, lakebase, sql
│   ├── router.py           # APX default router — extend with your own routers
│   ├── models.py           # APX default models — extend with your own
│   ├── api/                # YOUR route handlers (thin — delegate to services)
│   ├── services/           # YOUR business logic (no HTTP, no SQL)
│   ├── repositories/       # YOUR data access (SQL queries, Lakebase calls)
│   └── schemas/            # YOUR Pydantic request/response schemas
└── ui/
    ├── routes/             # TanStack Router pages
    ├── components/         # React + shadcn/ui components
    └── lib/                # Utilities (api client auto-generated from OpenAPI)
```

## Hello-World Baseline

The app starts with APX's default endpoints (`/version`, `/current-user`) and a basic
React page out of the box. The first task in Wave 4 is to add a `/api/sample` endpoint
that reads from the `gold_customer_summary` table, proving the app-to-lakehouse data
flow works end-to-end. Once that is confirmed, Claude replaces the sample endpoint with
the real industry-specific API during `/plan` + `/build-next`.

## Rules

1. **Keep APX's core/ untouched** — it handles config, auth, Lakebase connection, static files.
2. **Add your routes in `api/`** — register them in `router.py` or a new router file.
3. **Business logic in `services/`** — never in route handlers.
4. **Data access in `repositories/`** — never import SQL in services.
5. **Use APX's Dependencies** — `Dependencies.Session` for Lakebase, `Dependencies.Sql`.

## Authentication Patterns

| Client | When to Use | Auth Source |
|--------|-------------|-------------|
| **SP Client** (`ClientDependency`) | SQL queries, data access | App's service principal |
| **OBO Client** (`UserWorkspaceClientDependency`) | User identity operations | \
`X-Forwarded-Access-Token` header |

**Important:** SQL queries MUST use the SP client. OBO tokens lack the `sql` scope.

```python
# Correct — SP client for SQL
from core.dependencies import ClientDependency
client = ClientDependency()
result = client.execute_statement(...)

# Correct — OBO client for user identity
from core.dependencies import UserWorkspaceClientDependency
user_client = UserWorkspaceClientDependency()
me = user_client.current_user.me()
```

## SQL Warehouse Configuration

In `databricks.yml`, the app must have a `sql-warehouse` resource:

```yaml
resources:
  apps:
    {app_name}:
      resources:
        - name: sql-warehouse
          sql_warehouse:
            id: ${{var.warehouse_id}}
            permission: CAN_USE
```

In `app.yml`, reference it via `valueFrom`:

```yaml
env:
  - name: DATABRICKS_SQL_WAREHOUSE_ID
    valueFrom: sql-warehouse
```

## Statement Execution API Patterns

Use **named parameters** (`:param`) with `StatementParameterListItem`:

```python
from databricks.sdk.service.sql import StatementParameterListItem

statement = client.statement_execution.execute_statement(
    warehouse_id=warehouse_id,
    statement="SELECT * FROM table WHERE id = :id",
    parameters=[StatementParameterListItem(name="id", value=entity_id)],
)
```

## UI Components

**Always use shadcn/ui** from `components/ui/` — never hand-roll UI primitives.

Pre-installed components: button, card, table, badge, input, skeleton, dialog, \
tabs, select, separator.

Add more via: `npx shadcn@latest add <component> --yes` (run from the `ui/` directory).

## Deployment

Deploy from the **project root** (not from this directory):

```bash
./scripts/deploy-app.sh dev    # Build + bundle deploy + app deploy + SP permissions
```

## Dev Commands

```bash
apx dev start     # Start backend + frontend with hot reload
apx dev logs      # View logs
apx dev status    # Check server status
apx dev stop      # Stop all servers
apx dev check     # TypeScript + Python lint
apx build         # Production build
```

## Project CLAUDE.md

For full project context (tech stack, waves, deployment), see the root-level
`CLAUDE.md` in the parent project directory.
"""


# ---------------------------------------------------------------------------
# App README content
# ---------------------------------------------------------------------------


def write_app_readme(context: ScaffoldContext, app_dir: Path) -> None:
    """Write a comprehensive README for the app directory."""
    app_slug = context.app_name.replace("-", "_")
    readme_content = f"""\
# {context.app_name}

> Full-stack Databricks App built with \
[APX](https://github.com/databricks-solutions/apx) + 3-layer backend architecture.

## Setup

### 1. Configure `.env`

The `.env` file should contain:

```env
DATABRICKS_CONFIG_PROFILE={context.databricks_profile or "DEFAULT"}
DATABRICKS_SQL_WAREHOUSE_ID={context.warehouse_id}
CATALOG={context.catalog}
APP_NAME={context.app_name}
```

### 2. Local Development

```bash
apx dev start     # Start backend + frontend with hot reload
apx dev logs      # View logs
apx dev status    # Check server status
apx dev stop      # Stop all servers
```

### 3. Deployment

Deploy from the **project root** (not from this directory):

```bash
./scripts/deploy-app.sh dev
```

This runs: `apx build` -> `bundle deploy` -> `apps deploy` -> SP permissions.

## Architecture

```
src/{app_slug}/
├── backend/
│   ├── app.py              # FastAPI app factory
│   ├── core/               # APX internals (DO NOT MODIFY)
│   ├── router.py           # Default routes (/version, /current-user)
│   ├── api/                # YOUR route handlers (thin — delegate to services)
│   ├── services/           # YOUR business logic (no HTTP, no SQL)
│   ├── repositories/       # YOUR data access (SQL queries only)
│   └── schemas/            # YOUR Pydantic request/response schemas
└── ui/
    ├── routes/             # TanStack Router pages
    ├── components/         # React + shadcn/ui components
    └── lib/                # Utilities (auto-generated API client)
```

## Authentication

| Client | When to Use | Auth Source |
|--------|-------------|-------------|
| **SP Client** (`ClientDependency`) | SQL queries, data access | \
App's service principal |
| **OBO Client** (`UserWorkspaceClientDependency`) | User identity operations | \
`X-Forwarded-Access-Token` header |

**Important:** SQL queries MUST use the SP client. OBO tokens lack the `sql` scope.

## Code Quality

```bash
apx dev check     # TypeScript + Python lint
apx build         # Production build
```
"""
    readme_path = app_dir / "README.md"
    readme_path.write_text(readme_content, encoding="utf-8")
    logger.info("Wrote app README.md to %s", readme_path)
