# Framework Integration: ggen + Your Stack

This guide shows how ggen integrates with popular frameworks and development workflows.

## Next.js Integration

### Project Structure
```
my-next-app/
├── ggen.toml                    # ggen configuration
├── make.toml                    # Next.js lifecycle
├── templates/
│   ├── next-page.tmpl          # React page component
│   ├── next-api.tmpl           # API route
│   ├── next-layout.tmpl        # Layout component
│   └── next-config.tmpl        # next.config.js
├── data/
│   └── domain.ttl              # App domain model
└── generated/                  # Generated code
```

### Next.js Lifecycle
```toml
# make.toml
[lifecycle.init]
description = "Initialize Next.js project"
commands = [
    "npx create-next-app@latest . --typescript --tailwind --eslint --app",
    "mkdir -p templates data generated",
    "ggen template generate templates/next-config.tmpl"
]

[lifecycle.dev]
description = "Start development server"
commands = [
    "npm run dev"
]
watch = "**/*.{js,ts,jsx,tsx}"

[lifecycle.generate]
description = "Generate components and pages"
commands = [
    "ggen template generate templates/next-page.tmpl --var name=\"about\"",
    "ggen template generate templates/next-api.tmpl --var name=\"users\""
]

[lifecycle.build]
description = "Build for production"
commands = [
    "npm run build",
    "npm run export"
]

[lifecycle.deploy]
description = "Deploy to Vercel"
commands = [
    "vercel --prod"
]
```

### Next.js Templates

#### Page Component Template
```yaml
---
to: "src/app/{{ name }}/page.tsx"
vars:
  name: "{{ name }}"
  title: "{{ title | default(name | title) }}"
prefixes:
  ex: "http://example.org/next-app/"
sparql:
  find_components: "SELECT ?comp WHERE { ?comp a ex:Component }"
---

'use client';

import { Metadata } from 'next';

export const metadata: Metadata = {
  title: '{{ title }}',
  description: 'Generated {{ name }} page',
};

export default function {{ name | pascal }}Page() {
  return (
    <div className="container mx-auto px-4">
      <h1 className="text-3xl font-bold">{{ title }}</h1>
      <p>This page was generated by ggen</p>
    </div>
  );
}
```

#### API Route Template
```yaml
---
to: "src/app/api/{{ name }}/route.ts"
vars:
  name: "{{ name }}"
  method: "{{ method | default('GET') }}"
sparql:
  find_endpoints: "SELECT ?endpoint WHERE { ?endpoint a ex:APIEndpoint }"
---

import { NextRequest, NextResponse } from 'next/server';

export async function {{ method }}(
  request: NextRequest,
  { params }: { params: { {{ name }}: string } }
) {
  try {
    // Generated API endpoint for {{ name }}
    const data = {
      id: params.{{ name }},
      timestamp: new Date().toISOString(),
      generated: true
    };

    return NextResponse.json(data);
  } catch (error) {
    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    );
  }
}
```

## Rails Integration

### Rails Lifecycle
```toml
[lifecycle.init]
description = "Initialize Rails project"
commands = [
    "rails new . --api --database=postgresql",
    "bundle install"
]

[lifecycle.setup]
description = "Setup development environment"
commands = [
    "rails db:create db:migrate",
    "rails db:seed"
]

[lifecycle.generate]
description = "Generate Rails components"
commands = [
    "ggen template generate templates/rails-model.tmpl",
    "ggen template generate templates/rails-controller.tmpl",
    "ggen template generate templates/rails-migration.tmpl"
]

[lifecycle.dev]
description = "Start Rails server"
commands = [
    "rails server"
]
watch = "**/*.{rb,erb,yml}"

[lifecycle.test]
description = "Run Rails tests"
commands = [
    "rails test",
    "rspec"
]
```

## Django Integration

### Django Lifecycle
```toml
[lifecycle.init]
description = "Initialize Django project"
commands = [
    "django-admin startproject myproject .",
    "python manage.py startapp myapp"
]

[lifecycle.setup]
description = "Setup Django environment"
commands = [
    "python manage.py migrate",
    "python manage.py createsuperuser"
]

[lifecycle.generate]
description = "Generate Django components"
commands = [
    "ggen template generate templates/django-model.tmpl",
    "ggen template generate templates/django-view.tmpl",
    "ggen template generate templates/django-url.tmpl"
]
```

## Docker Integration

### Multi-stage Dockerfile Template
```yaml
---
to: "Dockerfile"
vars:
  base_image: "{{ base_image | default('rust:1.75') }}"
  app_name: "{{ app_name }}"
sparql:
  find_dependencies: "SELECT ?dep WHERE { ?dep a ex:Dependency }"
---

# Build stage
FROM {{ base_image }} as builder

WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY src ./src

RUN cargo build --release

# Runtime stage
FROM debian:bookworm-slim

RUN apt-get update && apt-get install -y \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=builder /app/target/release/{{ app_name }} .

EXPOSE 8080
CMD ["./{{ app_name }}"]
```

## Kubernetes Integration

### K8s Deployment Template
```yaml
---
to: "k8s/deployment.yaml"
vars:
  app_name: "{{ app_name }}"
  image: "{{ image }}"
  replicas: "{{ replicas | default(3) }}"
sparql:
  find_services: "SELECT ?svc WHERE { ?svc a ex:Microservice }"
---

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ app_name }}
  labels:
    app: {{ app_name }}
spec:
  replicas: {{ replicas }}
  selector:
    matchLabels:
      app: {{ app_name }}
  template:
    metadata:
      labels:
        app: {{ app_name }}
    spec:
      containers:
      - name: {{ app_name }}
        image: {{ image }}
        ports:
        - containerPort: 8080
        env:
        - name: RUST_LOG
          value: "info"
```

## CI/CD Integration

### GitHub Actions Workflow
```yaml
---
to: ".github/workflows/ci.yml"
vars:
  rust_version: "{{ rust_version | default('1.75') }}"
sparql:
  find_test_commands: "SELECT ?cmd WHERE { ?cmd a ex:TestCommand }"
---

name: CI

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

env:
  CARGO_TERM_COLOR: always

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3

    - name: Install Rust
      uses: dtolnay/rust-toolchain@master
      with:
        toolchain: {{ rust_version }}

    - name: Cache dependencies
      uses: Swatinem/rust-cache@v2

    - name: Run tests
      run: |
        {% for cmd in sparql_results.find_test_commands %}
        {{ cmd.cmd }}
        {% endfor %}

    - name: Generate code coverage
      uses: codecov/codecov-action@v3
```

## IDE Integration

### VSCode Configuration
```json
{
  "ggen.templates.path": "./templates",
  "ggen.ai.provider": "openai",
  "ggen.lifecycle.autoWatch": true,
  "files.associations": {
    "*.tmpl": "yaml"
  },
  "emmet.includeLanguages": {
    "tera": "html"
  }
}
```

### VSCode Tasks
```json
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "ggen: generate",
      "type": "shell",
      "command": "ggen",
      "args": ["template", "generate", "${fileBasename}"],
      "group": "build",
      "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": false,
        "panel": "shared"
      }
    },
    {
      "label": "ggen: lifecycle run",
      "type": "shell",
      "command": "ggen",
      "args": ["lifecycle", "run", "${input:phase}"],
      "group": "build"
    }
  ]
}
```

## Git Integration

### Pre-commit Hooks
```yaml
# .pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: ggen-format
        name: ggen format generated code
        entry: ggen lifecycle run format
        language: system
        files: ^generated/
      - id: ggen-validate
        name: ggen validate templates
        entry: ggen template validate
        language: system
        files: \.tmpl$
```

### Branch-based Templates
```toml
# make.toml
[lifecycle.generate]
description = "Generate based on current branch"
commands = [
    "ggen template generate templates/$(git branch --show-current).tmpl"
]
```

## Framework-Specific Patterns

### React Component Generation
```bash
# Generate React component with props
ggen ai generate --description "React component for user profile with avatar, name, and bio props"

# Output includes TypeScript interfaces, JSX, and tests
```

### Database Migration Generation
```bash
# Generate migration based on domain model
ggen template generate templates/migration.tmpl --var table="users"

# Template queries RDF for column definitions
# Generates proper SQL with constraints and indexes
```

### API Documentation Generation
```bash
# Generate OpenAPI spec from domain model
ggen template generate templates/openapi-spec.tmpl

# Template converts RDF entities to OpenAPI schema
# Includes request/response examples
```

## Migration from Existing Tools

### From Create React App to ggen
```bash
# Before: npx create-react-app my-app
# After:
ggen lifecycle init --template react-app
ggen lifecycle run setup
ggen lifecycle run dev
```

### From Rails Scaffolding to ggen
```bash
# Before: rails generate scaffold User name:string email:string
# After:
ggen template generate templates/rails-scaffold.tmpl --var model="User"
```

## Best Practices

### 1. Start with Framework Lifecycle
```bash
# Use framework-specific lifecycle
ggen lifecycle run init  # Creates proper structure
ggen lifecycle run setup # Installs dependencies correctly
```

### 2. Use Framework-Specific Templates
```bash
# Don't use generic templates for framework-specific code
ggen template generate templates/next-page.tmpl  # ✅ Good
ggen template generate templates/generic-file.tmpl  # ❌ Avoid
```

### 3. Integrate with Framework Tools
```bash
# Run framework linters after generation
[lifecycle.generate]
commands = [
    "ggen template generate templates/component.tmpl",
    "npm run lint generated/"
]
```

### 4. Version Control Integration
```bash
# Generate code in feature branches
git checkout -b feature/new-component
ggen template generate templates/component.tmpl
git add generated/
git commit -m "feat: add new component"
```

## Troubleshooting Framework Integration

### "Template doesn't match framework conventions"
**Solution**: Check template variables match framework expectations
```bash
# Verify template variables
ggen template debug templates/next-page.tmpl

# Check framework-specific requirements
ggen lifecycle run validate --framework nextjs
```

### "Generated code doesn't compile"
**Solution**: Use framework-specific validation
```bash
# Validate against framework rules
ggen template validate templates/next-page.tmpl --framework nextjs

# Check for framework-specific imports
grep -r "import.*next" generated/
```

### "Lifecycle conflicts with framework commands"
**Solution**: Customize lifecycle for your framework
```toml
[lifecycle.dev]
commands = [
    "npm run dev"  # Instead of generic dev server
]
```

## Advanced Framework Patterns

### Microservices Architecture
```toml
[lifecycle.generate]
description = "Generate microservice components"
commands = [
    "ggen template generate templates/service.tmpl --var name=\"user-service\"",
    "ggen template generate templates/api-gateway.tmpl",
    "ggen template generate templates/service-registry.tmpl"
]
```

### Event-Driven Architecture
```toml
[lifecycle.generate]
description = "Generate event-driven components"
commands = [
    "ggen template generate templates/event-producer.tmpl",
    "ggen template generate templates/event-consumer.tmpl",
    "ggen template generate templates/message-queue.tmpl"
]
```

### Multi-tenant Architecture
```toml
[lifecycle.generate]
description = "Generate multi-tenant components"
commands = [
    "ggen template generate templates/tenant-model.tmpl",
    "ggen template generate templates/tenant-middleware.tmpl",
    "ggen template generate templates/tenant-router.tmpl"
]
```

## Performance Optimization

### Framework-Specific Optimizations
```toml
[lifecycle.build]
description = "Optimized build for production"
commands = [
    "ggen template generate templates/build-config.tmpl",
    "npm run build",
    "ggen lifecycle run optimize-bundle"
]

[lifecycle.optimize-bundle]
description = "Framework-specific bundle optimization"
commands = [
    "npm run analyze",  # Next.js bundle analyzer
    "npm run optimize"  # Framework-specific optimizations
]
```

## Security Integration

### Framework Security Templates
```toml
[lifecycle.security]
description = "Security hardening"
commands = [
    "ggen template generate templates/security-headers.tmpl",
    "ggen template generate templates/cors-config.tmpl",
    "ggen template generate templates/auth-middleware.tmpl"
]
```

## Testing Integration

### Framework Testing Workflows
```toml
[lifecycle.test]
description = "Comprehensive testing"
commands = [
    "npm run test:unit",
    "npm run test:integration",
    "npm run test:e2e",
    "ggen template generate templates/test-coverage.tmpl"
]
```

## Deployment Integration

### Framework Deployment Templates
```toml
[lifecycle.deploy]
description = "Deploy to production"
commands = [
    "ggen template generate templates/dockerfile.tmpl",
    "ggen template generate templates/kubernetes.tmpl",
    "docker build -t my-app .",
    "kubectl apply -f generated/k8s/"
]
```

This integration guide shows how ggen works with your existing framework stack, not as a replacement for it.
