backend_path := "backend"
frontend_path := "frontend"

# Run backend + frontend watchers in split tmux panes (run from inside tmux)
[group('dev')]
watch:
    #!/usr/bin/env bash
    tmux split-window -h 'just watch-frontend'
    just watch-backend

# Run the backend with hot reload
[group('dev')]
watch-backend:
    cd {{backend_path}} && cargo watch -q -c -w src/ -x run

# Run the frontend dev server
[group('dev')]
watch-frontend:
    cd {{frontend_path}} && pnpm dev

# Run the backend tests in watch mode (sets up the test DB first)
[group('test')]
watch-test: test-db-setup
    cd {{backend_path}} && cargo watch -q -c -w src/ -x test

# Run the Playwright e2e suite (sets up the test DB + servers)
[group('test')]
e2e:
    mkdir -p /tmp/loft-files-test
    cd {{backend_path}} && set -a && . ./.env.test && set +a && (sqlx database create 2>/dev/null || true) && sqlx migrate run
    docker compose exec -T db psql -U postgres -d loft_test -c "TRUNCATE users, sessions, file_records CASCADE"
    cd {{frontend_path}} && pnpm exec playwright test

# Format backend + frontend
[group('quality')]
fmt: fmt-backend fmt-frontend

# Format the backend (cargo fmt)
[group('quality')]
fmt-backend:
    cd {{backend_path}} && cargo fmt

# Format the frontend (prettier)
[group('quality')]
fmt-frontend:
    cd {{frontend_path}} && pnpm exec prettier --write .

# Lint the backend (cargo clippy)
[group('quality')]
lint-backend:
    cd {{backend_path}} && cargo clippy

# Stage the given files (git add)
[group('git')]
stage +files:
    git add {{files}}

# Commit staged changes with a message
[group('git')]
commit message:
    git commit -m "{{message}}"

# Commit staged changes with a Claude co-author trailer
[group('git')]
co-commit message:
    git commit -m "{{message}}" -m "Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>"

# Push main to both the github and gitea remotes
[group('git')]
push:
    git push -u github main && git push -u gitea main

# Create (if missing) + migrate the test database
[group('db')]
test-db-setup: db-up
    cd {{backend_path}} && set -a && . ./.env.test && set +a && (sqlx database create 2>/dev/null || true) && sqlx migrate run

# Bring up the dev database container
[group('db')]
db-up:
    docker compose up -d db

# Create (if missing) + migrate the dev database
[group('db')]
db-setup: db-up
    cd {{backend_path}} && set -a && . ./.env && set +a && (sqlx database create 2>/dev/null || true) && sqlx migrate run

# Apply pending migrations to the dev database
[group('db')]
migrate:
    cd {{backend_path}} && set -a && . ./.env && set +a && sqlx migrate run

# Open a psql shell on the dev database
[group('db')]
db-shell:
    docker compose exec db psql -U postgres -d loft

# Run a SQL query against the dev database
[group('db')]
db-query query:
    docker compose exec db psql -U postgres -d loft -c "{{query}}"

# Open a shell inside the app container
[group('db')]
app-shell:
    docker compose exec app sh
