package setup

import (
	"fmt"
	"os"
)

const aiderConfigTemplate = `# Beads Issue Tracking Integration for Aider
# Auto-generated by 'bd setup aider'

# Load Beads workflow instructions for the AI
# This file is marked read-only and cached for efficiency
read:
  - .aider/BEADS.md
`

const aiderBeadsInstructions = `# Beads Issue Tracking Instructions for AI

This project uses **Beads (bd)** for issue tracking. Aider requires explicit command execution - suggest commands to the user.

## Core Workflow Rules

1. **Track ALL work in bd** (never use markdown TODOs or comment-based task lists)
2. **Suggest 'bd ready'** to find available work
3. **Suggest 'bd create'** for new issues/tasks/bugs
4. **Suggest 'bd sync'** at end of session
5. **ALWAYS suggest commands** - user will run them via /run

## Quick Command Reference (suggest these to user)

- ` + "`bd ready`" + ` - Show unblocked issues
- ` + "`bd list --status=open`" + ` - List all open issues
- ` + "`bd create --title=\"...\" --type=task`" + ` - Create new issue
- ` + "`bd update <id> --status=in_progress`" + ` - Claim work
- ` + "`bd close <id>`" + ` - Mark complete
- ` + "`bd dep add <issue> <depends-on>`" + ` - Add dependency (issue depends on depends-on)
- ` + "`bd sync`" + ` - Sync with git remote

## Workflow Pattern to Suggest

1. **Check ready work**: "Let's run ` + "`/run bd ready`" + ` to see what's available"
2. **Claim task**: "Run ` + "`/run bd update <id> --status=in_progress`" + ` to claim it"
3. **Do the work**
4. **Complete**: "Run ` + "`/run bd close <id>`" + ` when done"
5. **Sync**: "Run ` + "`/run bd sync`" + ` to push changes"

## Context Loading

Suggest ` + "`/run bd prime`" + ` for complete workflow documentation (~1-2k tokens).

## Issue Types

- ` + "`bug`" + ` - Something broken that needs fixing
- ` + "`feature`" + ` - New functionality
- ` + "`task`" + ` - Work item (tests, docs, refactoring)
- ` + "`epic`" + ` - Large feature composed of multiple issues
- ` + "`chore`" + ` - Maintenance work (dependencies, tooling)

## Priorities

- ` + "`0`" + ` - Critical (security, data loss, broken builds)
- ` + "`1`" + ` - High (major features, important bugs)
- ` + "`2`" + ` - Medium (nice-to-have features, minor bugs)
- ` + "`3`" + ` - Low (polish, optimization)
- ` + "`4`" + ` - Backlog (future ideas)

## Important Notes

- **Always use /run prefix** - Aider requires explicit command execution
- **Link discovered work** - Use ` + "`--deps discovered-from:<parent-id>`" + ` when creating issues found during work
- **Include descriptions** - Always provide meaningful context when creating issues
- **End session with sync** - Remind user to run ` + "`/run bd sync`" + ` before ending session

For detailed docs: see AGENTS.md, QUICKSTART.md, or run ` + "`bd --help`" + `
`

const aiderReadmeTemplate = `# Aider + Beads Integration

This project uses [Beads (bd)](https://github.com/steveyegge/beads) for issue tracking.

## How This Works with Aider

**Important**: Aider requires you to explicitly run commands using the ` + "`/run`" + ` command.
The AI will **suggest** bd commands, but you must confirm them.

## Quick Start

1. Check for available work:
   ` + "```bash" + `
   /run bd ready
   ` + "```" + `

2. Create new issues:
   ` + "```bash" + `
   /run bd create "Issue title" --description="Details" -t bug|feature|task -p 1
   ` + "```" + `

3. Claim work:
   ` + "```bash" + `
   /run bd update bd-42 --status in_progress
   ` + "```" + `

4. Complete work:
   ` + "```bash" + `
   /run bd close bd-42 --reason "Done"
   ` + "```" + `

5. Sync at end of session:
   ` + "```bash" + `
   /run bd sync
   ` + "```" + `

## Configuration

The ` + "`.aider.conf.yml`" + ` file contains instructions for the AI about bd workflow.
The AI will read these instructions and suggest appropriate bd commands.

## Workflow

Ask the AI questions like:
- "What issues are ready to work on?"
- "Create an issue for this bug I found"
- "Show me the details of bd-42"
- "Mark bd-42 as complete"

The AI will suggest the appropriate ` + "`bd`" + ` command, which you run via ` + "`/run`" + `.

## Issue Types

- ` + "`bug`" + ` - Something broken
- ` + "`feature`" + ` - New functionality
- ` + "`task`" + ` - Work item (tests, docs, refactoring)
- ` + "`epic`" + ` - Large feature with subtasks
- ` + "`chore`" + ` - Maintenance work

## Priorities

- ` + "`0`" + ` - Critical (security, data loss, broken builds)
- ` + "`1`" + ` - High (major features, important bugs)
- ` + "`2`" + ` - Medium (default, nice-to-have)
- ` + "`3`" + ` - Low (polish, optimization)
- ` + "`4`" + ` - Backlog (future ideas)

## More Information

- Run ` + "`bd --help`" + ` for full command reference
- See ` + "`AGENTS.md`" + ` for detailed AI integration docs
- See ` + "`QUICKSTART.md`" + ` for human-oriented guide
`

// InstallAider installs Aider integration
func InstallAider() {
	configPath := ".aider.conf.yml"
	instructionsPath := ".aider/BEADS.md"
	readmePath := ".aider/README.md"

	fmt.Println("Installing Aider integration...")

	// Ensure .aider directory exists
	if err := EnsureDir(".aider", 0755); err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}

	// Write config file
	if err := atomicWriteFile(configPath, []byte(aiderConfigTemplate)); err != nil {
		fmt.Fprintf(os.Stderr, "Error: write config: %v\n", err)
		os.Exit(1)
	}

	// Write instructions file (loaded by AI)
	if err := atomicWriteFile(instructionsPath, []byte(aiderBeadsInstructions)); err != nil {
		fmt.Fprintf(os.Stderr, "Error: write instructions: %v\n", err)
		os.Exit(1)
	}

	// Write README (for humans)
	if err := atomicWriteFile(readmePath, []byte(aiderReadmeTemplate)); err != nil {
		fmt.Fprintf(os.Stderr, "Error: write README: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("\n✓ Aider integration installed\n")
	fmt.Printf("  Config: %s\n", configPath)
	fmt.Printf("  Instructions: %s (loaded by AI)\n", instructionsPath)
	fmt.Printf("  README: %s (for humans)\n", readmePath)
	fmt.Println("\nUsage:")
	fmt.Println("  1. Start aider in this directory")
	fmt.Println("  2. Ask AI for available work (it will suggest: /run bd ready)")
	fmt.Println("  3. Run suggested commands using /run")
	fmt.Println("\nNote: Aider requires you to explicitly run commands via /run")
}

// CheckAider checks if Aider integration is installed
func CheckAider() {
	configPath := ".aider.conf.yml"

	if _, err := os.Stat(configPath); os.IsNotExist(err) {
		fmt.Println("✗ Aider integration not installed")
		fmt.Println("  Run: bd setup aider")
		os.Exit(1)
	}

	fmt.Println("✓ Aider integration installed:", configPath)
}

// RemoveAider removes Aider integration
func RemoveAider() {
	configPath := ".aider.conf.yml"
	instructionsPath := ".aider/BEADS.md"
	readmePath := ".aider/README.md"
	aiderDir := ".aider"

	fmt.Println("Removing Aider integration...")

	removed := false

	// Remove config
	if err := os.Remove(configPath); err != nil {
		if !os.IsNotExist(err) {
			fmt.Fprintf(os.Stderr, "Error: failed to remove config: %v\n", err)
			os.Exit(1)
		}
	} else {
		removed = true
	}

	// Remove instructions
	if err := os.Remove(instructionsPath); err != nil {
		if !os.IsNotExist(err) {
			fmt.Fprintf(os.Stderr, "Error: failed to remove instructions: %v\n", err)
			os.Exit(1)
		}
	} else {
		removed = true
	}

	// Remove README
	if err := os.Remove(readmePath); err != nil {
		if !os.IsNotExist(err) {
			fmt.Fprintf(os.Stderr, "Error: failed to remove README: %v\n", err)
			os.Exit(1)
		}
	} else {
		removed = true
	}

	// Try to remove .aider directory if empty
	if err := os.Remove(aiderDir); err != nil {
		// Ignore error - directory might not be empty or might not exist
	}

	if !removed {
		fmt.Println("No Aider integration files found")
		return
	}

	fmt.Println("✓ Removed Aider integration")
}
