promocrypt-cli 1.1.2

Command-line tool for promotional code generation
# CLAUDE.md — promocrypt-cli

> **Command-line interface for promotional code generation and validation**

---

## CRITICAL RULES

### 1. DOCUMENTATION FIRST (MANDATORY)

**Before making ANY code changes:**

1. **Update docs/ files FIRST** - Any logical changes, new features, or modifications require updating the relevant documentation files BEFORE writing code
2. **Update README.md** - Ensure README reflects current state, no outdated information
3. **Verify consistency** - Check that docs match the actual implementation

**This is REQUIRED. Users must never encounter outdated documentation or be unaware of changes.**

### 2. CLI is a Thin Wrapper

- CLI wraps promocrypt-core - don't duplicate core logic
- Use core's validation, generation, encryption directly
- CLI adds: database integration, output formatting, configuration

### 3. Exit Codes Matter

Scripts depend on exit codes. Always use correct codes:

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | Validation failed |
| 2 | File error |
| 3 | Auth error |
| 4 | Database error |
| 5 | Config error |
| 6 | Exec error |
| 7 | Not found |

### 4. JSON Mode Compatibility

When `-J` flag is used:
- All output must be valid JSON
- Success: `{"ok": true, "data": {...}}`
- Error: `{"ok": false, "error": {...}}`
- Never mix plain text with JSON output

### 5. Database Security

- Never log passwords or connection strings with credentials
- Escape all SQL identifiers and values
- Use parameterized queries where possible

---

## Quick Reference

```bash
# Create project
promocrypt create production -p "secret"

# Generate codes
promocrypt generate -n 1000 -d "postgres://..." -t codes

# Validate (also supports database lookup with --show-row)
promocrypt validate "ABC123DEF0"
promocrypt validate -f codes.txt --summary
promocrypt validate "ABC123" -d "postgres://..." -t codes --show-row

# Info (also supports --stats for statistics)
promocrypt info
promocrypt info --stats -d "postgres://..." -t codes

# Export
promocrypt export -d "postgres://..." -t codes -o codes.csv -F csv

# Config encryption
promocrypt config --encrypt
promocrypt config --decrypt
```

---

## Project Structure

```
cli/
├── src/
│   ├── main.rs              # Entry point
│   ├── cli.rs               # Clap argument definitions
│   ├── error.rs             # CLI error types
│   ├── output.rs            # Output formatting
│   ├── config.rs            # Configuration handling
│   ├── config_encryption.rs # Config file encryption (machine-bound)
│   ├── paths.rs             # Path resolution
│   ├── json.rs              # JSON output helpers
│   ├── database/
│   │   ├── mod.rs           # Database trait
│   │   ├── postgres.rs      # PostgreSQL implementation
│   │   └── sqlite.rs        # SQLite implementation
│   └── commands/
│       ├── completions.rs
│       ├── config.rs        # Also handles --encrypt/--decrypt
│       ├── create.rs
│       ├── doctor.rs
│       ├── export.rs        # Export codes from database
│       ├── generate.rs
│       ├── generation_log.rs
│       ├── history.rs
│       ├── info.rs          # Also handles --stats
│       ├── init.rs
│       ├── list.rs
│       ├── master.rs
│       ├── pg_export.rs
│       ├── pg_import.rs
│       ├── remove.rs
│       ├── rotate_secret.rs
│       ├── update.rs
│       └── validate.rs      # Also handles --show-row
├── docs/
│   ├── commands.md          # All commands reference
│   ├── configuration.md     # Config hierarchy
│   ├── database.md          # Database integration
│   ├── errors.md            # Exit codes, errors
│   └── output-formats.md    # Output formats
└── tests/
    └── integration.rs
```

---

## Documentation Index

| Document | Contents |
|----------|----------|
| [docs/commands.md]docs/commands.md | Complete command reference with all options |
| [docs/database.md]docs/database.md | PostgreSQL, SQLite, typed columns, external commands |
| [docs/configuration.md]docs/configuration.md | Config hierarchy, TOML/JSON format, paths |
| [docs/output-formats.md]docs/output-formats.md | Plain, JSON, CSV, SQL, JSON mode |
| [docs/errors.md]docs/errors.md | Exit codes, error types, scripting tips |

---

## Key Features

### Database Integration

```bash
# PostgreSQL
promocrypt generate -n 10000 \
  -d "postgres://user:pass@localhost/db" \
  -t promo_codes \
  -I campaign_id=123 \
  -N created_at

# SQLite
promocrypt generate -n 1000 \
  -d "sqlite:///codes.db" \
  -t codes
```

### Typed Columns

```bash
-x campaign="Summer"      # String
-I discount_percent=20    # Integer
-B active=true            # Boolean
-N created_at             # Timestamp (NOW)
--set-json meta='{...}'   # JSON
--set-null expires_at     # NULL
```

### Output Formats

```bash
# Generate command outputs lines by default, JSON array with -J flag
promocrypt generate -n 10    # One code per line
promocrypt generate -n 10 -J # JSON wrapped output

# Export command supports format flag
promocrypt export -F csv     # CSV with headers
promocrypt export -F json    # JSON array
promocrypt export -F sql     # SQL INSERT statements
```

### Configuration Hierarchy

**App configuration** (global settings):
1. Command-line arguments
2. Environment variables
3. User config (`~/.config/promocrypt/config.toml`)
4. System config (`/etc/promocrypt/config.toml`)

**Project configuration** (per-project settings):
- `.promocrypt` - can be encrypted or plain TOML
- `.promocrypt.toml` - plain TOML
- `.promocrypt.json` - plain JSON

### Auto-Interactive Mode

When JSON mode (`-J`) is not enabled, interactive mode is automatic:
- Missing required parameters are prompted interactively
- All CLI arguments remain available for power users
- JSON mode returns errors instead of prompting

---

## Build & Test

```bash
# Build
cargo build --release

# Test
cargo test

# Install
cargo install --path .

# Generate completions
promocrypt completions bash > ~/.bash_completion.d/promocrypt
```