#!/usr/bin/env bash

# folder temp
TMP_DIR=$(mktemp -d)
DEST=".rules-phoenix"

echo "🚀 Clone Phoenix repo temp..."
git clone --depth=1 https://github.com/phoenixframework/phoenix.git "$TMP_DIR"

# create destination folder
echo "📂 Creating destination folder '$DEST'..."
mkdir -p "$DEST"

echo "📦 Create rules file..."
cat > "$DEST/rules.md" << 'EOF'
---
description: Phoenix Framework Rules for AI Coding Agents
version: 1.0
encoding: UTF-8
---

# Phoenix Framework Development Rules

## Overview

This file contains the official Phoenix Framework guides and rules for AI coding agents working on Phoenix projects. These rules help agents understand Phoenix conventions, patterns, and best practices.

## File Reference

**#file:rules-phoenix**

This tag indicates that this rules file contains Phoenix Framework specific guidance for coding agents.

## Phoenix Documentation Context

The `guides/` folder in this directory contains the complete Phoenix Framework documentation, including:

- **Getting Started**: Installation, project setup, and basic concepts
- **Routing**: URL routing, controllers, and request handling
- **Controllers**: Request processing, actions, and responses
- **Views & Templates**: Rendering HTML, layouts, and view helpers
- **Contexts**: Domain logic organization and data access patterns
- **Ecto**: Database integration, schemas, migrations, and queries
- **Channels**: Real-time communication with WebSockets
- **LiveView**: Interactive web applications without JavaScript
- **Testing**: Unit tests, integration tests, and test patterns
- **Deployment**: Production deployment strategies

## Core Phoenix Principles

### 1. Convention over Configuration
- Follow Phoenix naming conventions for modules, files, and functions
- Use standard directory structure for Phoenix applications
- Leverage Phoenix generators for consistent code patterns

### 2. Context-Driven Design
- Organize business logic into bounded contexts
- Keep contexts focused on specific domain areas
- Use contexts as the API boundary for business logic

### 3. Functional Programming Patterns
- Prefer immutable data structures
- Use pattern matching for control flow
- Leverage pipe operators for data transformation
- Handle errors with `{:ok, result}` and `{:error, reason}` tuples

### 4. Real-time by Default
- Design with real-time features in mind
- Use Phoenix Channels for WebSocket communication
- Leverage LiveView for interactive interfaces
- Implement PubSub for decoupled real-time updates

## Development Guidelines

### Code Organization
- Place business logic in contexts, not controllers
- Keep controllers thin - delegate to contexts
- Use schemas for data validation and casting
- Organize tests to mirror application structure

### Database Patterns
- Use Ecto for all database interactions
- Define schemas with proper validations
- Create focused migration files
- Use transactions for complex operations

### Testing Strategy
- Write comprehensive tests for contexts
- Test controller actions and responses
- Use factories for test data creation
- Mock external dependencies appropriately

### Performance Considerations
- Leverage Elixir's concurrent processing model
- Use GenServers for stateful processes
- Implement proper caching strategies
- Monitor and optimize database queries

## Agent Instructions

When working on Phoenix projects, AI coding agents should:

1. **Reference the guides**: Always consult the Phoenix guides in this directory for authoritative information
2. **Follow conventions**: Adhere to Phoenix naming and structural conventions
3. **Use contexts**: Organize business logic within appropriate contexts
4. **Write tests**: Include comprehensive tests for all new functionality
5. **Handle errors**: Use proper error handling patterns with tuples
6. **Consider real-time**: Think about real-time features and user experience
7. **Optimize queries**: Be mindful of database query efficiency
8. **Follow Elixir patterns**: Use functional programming idioms and OTP principles

## Usage with Different AI Agents

This rules file is compatible with various AI coding agents:

- **Claude Code**: Reference with `@.rules-phoenix/rules.md`
- **Cursor**: Include in project context or workspace rules
- **GitHub Copilot**: Reference in project documentation
- **Other agents**: Include as context or reference material

## Updating Guidelines

To keep these rules current:

1. Re-run the download script periodically to get latest Phoenix guides
2. Review Phoenix changelogs for new patterns and conventions
3. Update rules based on team-specific patterns and preferences
4. Maintain consistency with Phoenix community best practices

---

*Phoenix Framework documentation downloaded from: https://github.com/phoenixframework/phoenix*
*Generated by: download-phoenix-guides script*
*Last updated: $(date +"%Y-%m-%d")*
EOF

echo "📁 Copying 'guides/' folder..."
cp -R "$TMP_DIR/guides" "$DEST"

echo "🧹 Cleaning up temporary files..."
rm -rf "$TMP_DIR"

echo "✅ Done! Files saved in ./$DEST"