#!/bin/bash

# Vibes Feature Generator
# Usage: ./create-feature.sh <feature-name>

set -e

# Colors for vibes
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if feature name provided
if [ $# -eq 0 ]; then
    echo "🌊 What should we call this feature?"
    read -p "Feature name: " FEATURE_NAME
else
    FEATURE_NAME=$1
fi

# Convert to lowercase and replace spaces with hyphens
FEATURE_NAME=$(echo "$FEATURE_NAME" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')

# Feature directory
FEATURE_DIR="features/$FEATURE_NAME"

# Check if already exists
if [ -d "$FEATURE_DIR" ]; then
    echo "❌ Feature '$FEATURE_NAME' already exists!"
    exit 1
fi

echo -e "${BLUE}🌊 Creating feature: $FEATURE_NAME${NC}"

# Create directory structure
mkdir -p "$FEATURE_DIR"/{ui/components,api/handlers,api/routes,logic/services,data/models,tests}

# Create package.json
cat > "$FEATURE_DIR/package.json" << EOF
{
  "name": "@features/$FEATURE_NAME",
  "version": "1.0.0",
  "main": "index.ts",
  "private": true,
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "@shared/api": "workspace:*"
  }
}
EOF

# Create AI metadata
cat > "$FEATURE_DIR/.ai-metadata.json" << EOF
{
  "name": "$FEATURE_NAME",
  "type": "feature",
  "architecture": "vertical-slice",
  "layers": {
    "ui": "User interface components and screens",
    "api": "HTTP endpoints and route handlers",
    "logic": "Business logic and service layer",
    "data": "Data models and repository pattern"
  },
  "status": "development",
  "dependencies": ["@shared/api"],
  "exports": []
}
EOF

# Create index.ts with AI-friendly comments
cat > "$FEATURE_DIR/index.ts" << EOF
/**
 * Public API for $FEATURE_NAME feature
 * AI-NAV: Entry point - all exports should be listed here
 * AI-PATTERN: Barrel export pattern
 */

// AI-SECTION: UI Components
// export { ExampleComponent } from './ui/components/ExampleComponent';
// export { ExampleScreen } from './ui/screens/ExampleScreen';

// AI-SECTION: API Routes
// export { routes } from './api/routes';
// export { handlers } from './api/handlers';

// AI-SECTION: Business Logic
// export { ExampleService } from './logic/services/ExampleService';

// AI-SECTION: Data Types
// export type { Example, CreateExampleInput } from './data/models/Example';
EOF

# Create example model with AI annotations
cat > "$FEATURE_DIR/data/models/Example.ts" << EOF
/**
 * Example data model
 * AI-LAYER: Data
 * AI-PATTERN: TypeScript interface for type safety
 */
export interface Example {
  id: string;
  name: string;
  createdAt: Date;
  updatedAt: Date;
}

// AI-PATTERN: Input types for CRUD operations
export type CreateExampleInput = Omit<Example, 'id' | 'createdAt' | 'updatedAt'>;
export type UpdateExampleInput = Partial<Omit<Example, 'id'>>;
EOF

# Create example service with AI annotations
cat > "$FEATURE_DIR/logic/services/ExampleService.ts" << EOF
/**
 * Example business logic service
 * AI-LAYER: Logic
 * AI-PATTERN: Service class with dependency injection
 * AI-DEPS: Depends on data layer models
 */
import { Example, CreateExampleInput } from '../../data/models/Example';

export class ExampleService {
  // AI-TODO: Inject repository dependency
  // constructor(private repository: ExampleRepository) {}

  async getAll(): Promise<Example[]> {
    // AI-IMPLEMENT: Add data fetching logic
    return [];
  }

  async create(input: CreateExampleInput): Promise<Example> {
    // AI-IMPLEMENT: Add creation logic with validation
    throw new Error('Not implemented');
  }

  async update(id: string, input: UpdateExampleInput): Promise<Example> {
    // AI-IMPLEMENT: Add update logic
    throw new Error('Not implemented');
  }

  async delete(id: string): Promise<void> {
    // AI-IMPLEMENT: Add deletion logic
    throw new Error('Not implemented');
  }
}
EOF

# Create example component with AI annotations
cat > "$FEATURE_DIR/ui/components/ExampleComponent.tsx" << EOF
/**
 * Example UI component
 * AI-LAYER: UI
 * AI-PATTERN: React functional component with TypeScript
 * AI-DEPS: May depend on logic layer for data
 */
import React from 'react';

interface ExampleComponentProps {
  title: string;
}

export const ExampleComponent: React.FC<ExampleComponentProps> = ({ title }) => {
  // AI-TODO: Add state management and effects
  // AI-TODO: Connect to service layer for data

  return (
    <div>
      <h2>{title}</h2>
      <p>Start building your feature here!</p>
    </div>
  );
};
EOF

# Create example API route with AI annotations
cat > "$FEATURE_DIR/api/routes/example.ts" << EOF
/**
 * Example API routes
 * AI-LAYER: API
 * AI-PATTERN: Express-style route definitions
 * AI-DEPS: Depends on handlers and logic layer
 */
import { Router } from 'express';
import { handlers } from '../handlers/example';

const router = Router();

// AI-ROUTES: RESTful endpoints
router.get('/api/${FEATURE_NAME}', handlers.list);
router.post('/api/${FEATURE_NAME}', handlers.create);
router.put('/api/${FEATURE_NAME}/:id', handlers.update);
router.delete('/api/${FEATURE_NAME}/:id', handlers.delete);

export { router as exampleRoutes };
EOF

# Create README with AI guidance
cat > "$FEATURE_DIR/README.md" << EOF
# $FEATURE_NAME

## Overview
Describe what this feature does.

## AI Navigation Guide

### Quick Links
- Entry point: \`index.ts\`
- UI components: \`ui/components/\`
- API routes: \`api/routes/\`
- Business logic: \`logic/services/\`
- Data models: \`data/models/\`

### Layer Responsibilities
1. **UI Layer** (\`ui/\`)
   - React components and screens
   - User interactions and state management
   - Connects to logic layer for data

2. **API Layer** (\`api/\`)
   - HTTP route definitions
   - Request/response handling
   - Input validation

3. **Logic Layer** (\`logic/\`)
   - Business rules and workflows
   - Service classes
   - Orchestrates data operations

4. **Data Layer** (\`data/\`)
   - TypeScript interfaces and types
   - Repository pattern (when needed)
   - Database models

## Usage
\`\`\`typescript
import { ExampleComponent } from '@features/$FEATURE_NAME';
\`\`\`

## Development Guidelines
- Keep all feature code within this directory
- Export public API through \`index.ts\`
- Don't import from other features directly
- Use \`@shared/\` for truly generic utilities
EOF

# Create AI assistant file
cat > "$FEATURE_DIR/README.ai.md" << EOF
# AI Assistant Guide: $FEATURE_NAME

## Feature Context
- **Purpose**: [Describe the feature's purpose]
- **Status**: Development
- **Dependencies**: @shared/api

## Common AI Tasks

### 1. Add a new component
- Location: \`ui/components/\`
- Pattern: React functional component with TypeScript
- Export in: \`ui/index.ts\` then \`index.ts\`

### 2. Add an API endpoint
- Route definition: \`api/routes/\`
- Handler: \`api/handlers/\`
- Pattern: RESTful conventions

### 3. Add business logic
- Location: \`logic/services/\`
- Pattern: Service class with dependency injection
- Export in: \`logic/index.ts\` then \`index.ts\`

### 4. Add a data model
- Location: \`data/models/\`
- Pattern: TypeScript interface
- Include: CRUD input types

## Code Generation Hints
- Use existing patterns in the codebase
- Follow naming conventions (PascalCase for components, camelCase for files)
- Add AI-friendly comments for complex logic
- Update exports in index files

## Testing
- Unit tests: \`tests/unit/\`
- Integration tests: \`tests/integration/\`
- Follow existing test patterns
EOF

echo -e "${GREEN}✅ Feature '$FEATURE_NAME' created with AI enhancements!${NC}"
echo
echo -e "${YELLOW}Next steps:${NC}"
echo "1. cd $FEATURE_DIR"
echo "2. Start adding your code"
echo "3. Export your public API in index.ts"
echo "4. Import in your apps: import { ... } from '@features/$FEATURE_NAME'"
echo
echo -e "${BLUE}🌊 Keep vibing with AI assistance!${NC}"