package skills

import (
	"os"
	"path/filepath"
	"time"
)

var builtinSkills = []Skill{
	{
		Name:        "env-setup",
		Description: "Set up a complete development environment for any language. Detects missing tools, installs them, and configures the project.",
		Author:      "muyue",
		Version:     "1.1.0",
		Target:      "both",
		Tags:        []string{"setup", "environment", "install"},
		Category:    "setup",
		Content: `# Environment Setup

Use this skill when setting up a new development environment or project.

## Steps

1. Detect the project type by checking for config files:
   - ` + "`go.mod`" + ` → Go
   - ` + "`package.json`" + ` → Node.js
   - ` + "`requirements.txt` / `pyproject.toml` / `setup.py`" + ` → Python
   - ` + "`Cargo.toml`" + ` → Rust
   - ` + "`pom.xml` / `build.gradle`" + ` → Java

2. Check if required tools are installed:
   - Language runtime (go, node, python, etc.)
   - Package manager (npm, pip, cargo, etc.)
   - Linter/formatter
   - Test runner

3. If tools are missing, install them using the system package manager:
   - Linux: apt/dnf/pacman
   - macOS: brew
   - Windows: winget/scoop

4. Install project dependencies:
   - ` + "`go mod download`" + ` for Go
   - ` + "`npm install`" + ` / ` + "`pnpm install`" + ` for Node.js
   - ` + "`pip install -r requirements.txt`" + ` / ` + "`uv sync`" + ` for Python
   - ` + "`cargo build`" + ` for Rust

5. Configure git hooks if ` + "`pre-commit`" + ` config exists.

6. Verify the setup by running tests or build.

## Error Handling

- If a tool cannot be installed automatically, provide the manual install command.
- If dependency installation fails, check for version conflicts and suggest fixes.
- Always check for lock files first to ensure reproducible installs.`,
	},
	{
		Name:        "git-workflow",
		Description: "Manage git branches, commits, and pull requests following best practices. Handles branching strategy, conventional commits, and PR creation.",
		Author:      "muyue",
		Version:     "1.1.0",
		Target:      "both",
		Tags:        []string{"git", "workflow", "branching", "commits"},
		Category:    "workflow",
		Dependencies: []SkillDependency{
			{Type: "tool", Name: "git", Required: true},
			{Type: "tool", Name: "gh", Required: false},
		},
		Content: `# Git Workflow

Use this skill when the user needs to create branches, make commits, or manage pull requests.

## Branch Naming Convention

- ` + "`feature/<ticket>-<description>`" + ` for new features
- ` + "`fix/<ticket>-<description>`" + ` for bug fixes
- ` + "`refactor/<description>`" + ` for refactoring
- ` + "`docs/<description>`" + ` for documentation

## Commit Messages

Follow Conventional Commits:
- ` + "`feat: add user authentication`" + `
- ` + "`fix: resolve null pointer in login`" + `
- ` + "`refactor: extract validation logic`" + `
- ` + "`docs: update API documentation`" + `
- ` + "`test: add integration tests for auth`" + `
- ` + "`chore: update dependencies`" + `

## Workflow

1. Before starting, pull latest changes: ` + "`git pull --rebase origin main`" + `
2. Create branch: ` + "`git checkout -b feature/my-feature`" + `
3. Make changes and commit frequently with meaningful messages
4. Before pushing, rebase: ` + "`git rebase origin/main`" + `
5. Push: ` + "`git push -u origin feature/my-feature`" + `
6. Create PR with description following template

## PR Description Template

` + "```" + `
## Summary
<1-3 bullet points>

## Changes
- <list of key changes>

## Test Plan
- [ ] <checklist>
` + "```" + `

## Error Handling

- If rebase has conflicts, help resolve them file by file
- If push is rejected, pull with rebase first
- Never force push to main/master`,
	},
	{
		Name:        "api-design",
		Description: "Design and implement REST or GraphQL APIs following best practices. Includes endpoint design, error handling, and documentation.",
		Author:      "muyue",
		Version:     "1.1.0",
		Target:      "both",
		Tags:        []string{"api", "rest", "graphql", "design"},
		Category:    "design",
		Content: `# API Design

Use this skill when designing or implementing an API.

## REST API Design Rules

1. Use nouns for resources, not verbs: ` + "`/users`" + ` not ` + "`/getUsers`" + `
2. Use plural nouns: ` + "`/users`" + ` not ` + "`/user`" + `
3. Use proper HTTP methods:
   - GET for reading
   - POST for creating
   - PUT/PATCH for updating
   - DELETE for removing
4. Use query parameters for filtering: ` + "`/users?role=admin&active=true`" + `
5. Use pagination: ` + "`/users?page=1&limit=20`" + `
6. Return proper status codes:
   - 200: Success
   - 201: Created
   - 204: No Content (successful delete)
   - 400: Bad Request
   - 401: Unauthorized
   - 403: Forbidden
   - 404: Not Found
   - 422: Validation Error
   - 500: Internal Server Error

## Error Response Format

` + "```" + `json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Human readable message",
    "details": [
      {"field": "email", "message": "Invalid email format"}
    ]
  }
}
` + "```" + `

## Implementation Steps

1. Define the API spec (endpoints, request/response schemas)
2. Implement data models
3. Add validation middleware
4. Implement handlers
5. Add error handling
6. Write tests
7. Generate documentation (OpenAPI/Swagger)`,
	},
	{
		Name:        "debug-assist",
		Description: "Systematic debugging assistant. Helps identify, isolate, and fix bugs using a structured approach.",
		Author:      "muyue",
		Version:     "1.1.0",
		Target:      "both",
		Tags:        []string{"debug", "troubleshooting", "bugs"},
		Category:    "debugging",
		Content: `# Debug Assist

Use this skill when the user reports a bug or asks for help debugging.

## Debugging Process

1. **Reproduce** — Understand the exact steps to reproduce
2. **Isolate** — Narrow down the scope:
   - Is it frontend or backend?
   - Does it happen consistently or intermittently?
   - Does it happen in all environments or just one?
3. **Hypothesize** — Form a hypothesis about the root cause
4. **Verify** — Add logging or breakpoints to confirm
5. **Fix** — Make the minimal change to fix the issue
6. **Test** — Verify the fix works and does not break other things
7. **Prevent** — Add a test to prevent regression

## Common Patterns

- **Null/Nil errors**: Check for missing initialization or unexpected nil values
- **Type errors**: Check API contracts and type assertions
- **Race conditions**: Look for shared mutable state without synchronization
- **Memory leaks**: Check for unclosed resources (connections, files, channels)
- **Off-by-one**: Check loop bounds and array indexing
- **State issues**: Check if state is properly reset between operations

## Debugging Commands

- Check logs: Look for error messages and stack traces
- Check recent changes: ` + "`git diff HEAD~5`" + ` to see what changed
- Check dependencies: Verify versions match expected
- Check environment: Compare config between working and broken environments`,
	},
	{
		Name:        "code-review",
		Description: "Perform a thorough code review. Checks for bugs, security issues, performance problems, and style consistency.",
		Author:      "muyue",
		Version:     "1.1.0",
		Target:      "both",
		Tags:        []string{"review", "quality", "security"},
		Category:    "quality",
		Content: `# Code Review

Use this skill when reviewing code changes or pull requests.

## Review Checklist

### Correctness
- Does the code do what it is supposed to?
- Are edge cases handled?
- Are there off-by-one errors?
- Are error paths handled?

### Security
- Is user input sanitized?
- Are there SQL injection risks?
- Are secrets hardcoded?
- Are authentication/authorization checks in place?
- Is sensitive data logged?

### Performance
- Are there N+1 queries?
- Are there unnecessary loops or computations?
- Is caching used where appropriate?
- Are large allocations avoided?

### Readability
- Are names descriptive?
- Is the code self-documenting?
- Are complex parts commented?
- Is the code modular?

### Testing
- Are there unit tests?
- Are edge cases tested?
- Are error paths tested?
- Are tests independent and deterministic?

## Review Format

1. Summary of changes
2. Issues found (critical to minor)
3. Suggestions for improvement
4. Positive observations

## Severity Levels

- **Critical**: Security vulnerabilities, data loss risks, crashes
- **Major**: Bugs, performance issues, missing error handling
- **Minor**: Style issues, naming, minor refactoring opportunities
- **Suggestion**: Alternative approaches, improvements`,
	},
	{
		Name:        "docker-setup",
		Description: "Set up Docker and docker-compose for a project with best practices including multi-stage builds, health checks, and proper networking.",
		Author:      "muyue",
		Version:     "1.0.0",
		Target:      "both",
		Tags:        []string{"docker", "containers", "devops", "compose"},
		Category:    "devops",
		Dependencies: []SkillDependency{
			{Type: "tool", Name: "docker", Required: true},
		},
		Content: `# Docker Setup

Use this skill when the user needs Docker configuration for a project.

## Dockerfile Best Practices

1. Use multi-stage builds to reduce image size:
   - Builder stage: install dependencies, compile
   - Runtime stage: copy only the binary/artifacts

2. Use specific base image tags (not ` + "`latest`" + `):
   - ` + "`golang:1.24-alpine`" + ` for Go
   - ` + "`node:22-slim`" + ` for Node.js
   - ` + "`python:3.12-slim`" + ` for Python

3. Order layers for cache efficiency:
   - Copy dependency files first (go.mod, package.json, requirements.txt)
   - Install dependencies
   - Copy source code last

4. Add health checks:
   ` + "```" + `dockerfile
   HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:8080/health || exit 1
   ` + "```" + `

5. Run as non-root user:
   ` + "```" + `dockerfile
   RUN adduser -D appuser
   USER appuser
   ` + "```" + `

## docker-compose.yml Structure

` + "```" + `yaml
version: "3.9"
services:
  app:
    build: .
    ports:
      - "8080:8080"
    environment:
      - DATABASE_URL=postgres://user:pass@db:5432/app
    depends_on:
      db:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 3s
      retries: 3

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: app
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U user"]
      interval: 10s
      timeout: 3s
      retries: 5

volumes:
  pgdata:
` + "```" + `

## Error Handling

- If Docker is not installed, provide install instructions for the platform
- If port is already in use, suggest alternative ports
- If build fails, check for missing .dockerignore and suggest one`,
	},
	{
		Name:        "security-audit",
		Description: "Perform a security audit on code, dependencies, and configuration. Checks for OWASP Top 10 vulnerabilities, dependency vulnerabilities, and misconfigurations.",
		Author:      "muyue",
		Version:     "1.0.0",
		Target:      "both",
		Tags:        []string{"security", "audit", "vulnerabilities", "owasp"},
		Category:    "security",
		Content: `# Security Audit

Use this skill when the user needs a security review or vulnerability assessment.

## Audit Checklist

### Input Validation (OWASP A03:2021)
- All user input is validated and sanitized
- SQL queries use parameterized statements
- File paths are validated (no path traversal)
- Input length limits are enforced

### Authentication and Authorization (OWASP A07:2021)
- Passwords are hashed with bcrypt/argon2 (never MD5/SHA1)
- JWT tokens have short expiry with refresh rotation
- Session management is secure
- RBAC or ABAC is properly implemented
- API endpoints have proper auth checks

### Data Protection (OWASP A02:2021)
- Secrets are not in source code (use env vars or secret managers)
- Sensitive data is encrypted at rest and in transit
- PII is properly handled and not logged
- TLS is enforced for all connections

### Dependency Security (OWASP A06:2021)
- Run ` + "`npm audit`" + `, ` + "`pip audit`" + `, or ` + "`go vuln check`" + `
- Check for known CVEs in dependencies
- Keep dependencies up to date
- Use lock files for reproducible builds

### Configuration Security
- Debug mode is disabled in production
- CORS is properly configured
- Rate limiting is in place
- Security headers are set (CSP, HSTS, X-Frame-Options)
- Error messages do not leak internal details

## Automated Checks

Run these tools if available:
- ` + "`gosec ./...`" + ` for Go security
- ` + "`bandit -r .`" + ` for Python security
- ` + "`npm audit`" + ` for Node.js vulnerabilities
- ` + "`trivy fs .`" + ` for container/Dockerfile scanning

## Report Format

1. Executive Summary (risk level, total findings)
2. Critical findings (immediate action required)
3. High findings (fix within 24h)
4. Medium findings (fix within sprint)
5. Low findings (address when convenient)
6. Recommendations`,
	},
	{
		Name:        "mcp-setup",
		Description: "Configure MCP (Model Context Protocol) servers for AI tools. Discovers, installs, and configures MCP servers across multiple editors.",
		Author:      "muyue",
		Version:     "1.0.0",
		Target:      "both",
		Tags:        []string{"mcp", "ai", "configuration", "editors"},
		Category:    "setup",
		Dependencies: []SkillDependency{
			{Type: "tool", Name: "npx", Required: true},
		},
		Content: `# MCP Server Setup

Use this skill when the user wants to configure MCP servers for their AI coding tools.

## Supported Editors

Muyue can generate MCP configs for:
- **Crush**: ` + "`~/.config/crush/crush.json`" + ` (key: ` + "`mcps`" + `)
- **Claude Code**: ` + "`~/.claude.json`" + ` (key: ` + "`mcpServers`" + `)
- **Cursor**: ` + "`~/.cursor/mcp.json`" + ` (key: ` + "`mcpServers`" + `, adds ` + "`type: stdio`" + `)
- **VS Code**: ` + "`~/.vscode/mcp.json`" + ` (key: ` + "`servers`" + `)
- **Windsurf**: ` + "`~/.windsurf/mcp.json`" + ` (key: ` + "`mcpServers`" + `)

## Common MCP Servers

| Server | Package | Required Env |
|--------|---------|-------------|
| filesystem | @modelcontextprotocol/server-filesystem | None |
| fetch | @modelcontextprotocol/server-fetch | None |
| github | @modelcontextprotocol/server-github | GITHUB_PERSONAL_ACCESS_TOKEN |
| brave-search | @modelcontextprotocol/server-brave-search | BRAVE_API_KEY |
| memory | @modelcontextprotocol/server-memory | None |
| postgres | @modelcontextprotocol/server-postgres | DATABASE_URL |
| sqlite | @modelcontextprotocol/server-sqlite | None |
| docker | @modelcontextprotocol/server-docker | None |

## Setup Steps

1. Ask which editors the user wants to configure
2. Ask which MCP servers they need
3. For servers requiring API keys, prompt for the key
4. Generate configs for each selected editor
5. Validate configs (check JSON is valid, commands exist)
6. Test connectivity if possible

## Credential Management

- API keys should be stored in the Muyue config (encrypted)
- When generating MCP configs, inject keys from the Muyue config
- Never hardcode API keys in config files in version control
- Suggest adding MCP config files to ` + "`.gitignore`" + `

## Troubleshooting

- If npx fails, suggest ` + "`npm install -g`" + ` the package
- If a server does not start, check the command and args
- If auth fails, verify the API key is correct and active`,
	},
	{
		Name:        "lsp-setup",
		Description: "Configure Language Server Protocol servers for code intelligence. Detects project languages, installs LSPs, and generates editor configs.",
		Author:      "muyue",
		Version:     "1.0.0",
		Target:      "both",
		Tags:        []string{"lsp", "language-server", "ide", "configuration"},
		Category:    "setup",
		Content: `# LSP Server Setup

Use this skill when the user wants to set up language servers for code intelligence.

## Supported Languages

| Language | Server | Install Method |
|----------|--------|---------------|
| Go | gopls | ` + "`go install`" + ` |
| Python | pyright | ` + "`npm install -g`" + ` |
| TypeScript/JS | typescript-language-server | ` + "`npm install -g`" + ` |
| Rust | rust-analyzer | ` + "`rustup component add`" + ` |
| C/C++ | clangd | System package |
| Lua | lua-language-server | ` + "`npm install -g`" + ` |
| HTML | vscode-html-language-server | ` + "`npm install -g vscode-langservers-extracted`" + ` |
| CSS | vscode-css-language-server | ` + "`npm install -g vscode-langservers-extracted`" + ` |
| JSON | vscode-json-language-server | ` + "`npm install -g vscode-langservers-extracted`" + ` |
| YAML | yaml-language-server | ` + "`npm install -g`" + ` |
| Bash | bash-language-server | ` + "`npm install -g`" + ` |
| Docker | dockerfile-language-server | ` + "`npm install -g`" + ` |
| Vue | vue-language-server | ` + "`npm install -g`" + ` |
| Svelte | svelte-language-server | ` + "`npm install -g`" + ` |

## Auto-Detection

Detect project languages from:
- Config files: ` + "`go.mod`" + `, ` + "`package.json`" + `, ` + "`Cargo.toml`" + `, ` + "`pyproject.toml`" + `
- Source file extensions: ` + "`*.go`" + `, ` + "`*.py`" + `, ` + "`*.ts`" + `, ` + "`*.rs`" + `

## Editor Config Generation

### Neovim
Generate ` + "`lspconfig`" + ` setup snippet for each LSP.

### Helix
Generate ` + "`languages.toml`" + ` entries with language-server mappings.

### VS Code / Cursor
Generate ` + "`extensions.json`" + ` recommendations for each LSP.

## Health Checks

After installation, verify:
1. The binary is in PATH
2. The version matches expected
3. A basic ` + "`initialize`" + ` request succeeds (if applicable)`,
	},
	{
		Name:        "workflow-design",
		Description: "Design development workflows and automations. Creates CI/CD pipelines, git hooks, and development process documentation.",
		Author:      "muyue",
		Version:     "1.0.0",
		Target:      "both",
		Tags:        []string{"workflow", "ci-cd", "automation", "process"},
		Category:    "workflow",
		Content: `# Workflow Design

Use this skill when the user wants to establish development workflows or CI/CD pipelines.

## CI/CD Pipeline Design

### GitHub Actions Template

` + "```" + `yaml
name: CI
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with: { go-version: "1.24" }
      - run: go vet ./...
      - run: golint ./...

  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with: { go-version: "1.24" }
      - run: go test -race -coverprofile=coverage.out ./...
      - run: go tool cover -func=coverage.out

  build:
    needs: [lint, test]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: go build -o bin/app ./cmd/app
` + "```" + `

## Git Hooks

Use ` + "`pre-commit`" + ` framework:
- ` + "`pre-commit`" + `: lint, format check, trailing whitespace
- ` + "`commit-msg`" + `: validate conventional commit format
- ` + "`pre-push`" + `: run tests

## Branch Protection Rules

- Require PR reviews (at least 1 approval)
- Require status checks to pass
- Require up-to-date branch before merge
- Require linear history (rebase merge)

## Development Process

1. Pick a task from the backlog
2. Create a feature branch
3. Implement with tests
4. Run linter and tests locally
5. Push and create PR
6. Address review feedback
7. Merge when approved and CI passes
8. Delete feature branch

## Error Handling

- If CI fails, provide clear error output and suggested fixes
- If hooks fail, explain what failed and how to fix
- Suggest ` + "`--no-verify`" + ` only as a last resort, with a warning`,
	},
}

func InstallBuiltinSkills() error {
	dir, err := SkillsDir()
	if err != nil {
		return err
	}

	for _, s := range builtinSkills {
		skillDir := filepath.Join(dir, s.Name)
		skillPath := filepath.Join(skillDir, "SKILL.md")

		if _, err := os.Stat(skillPath); err == nil {
			continue
		}

		s.CreatedAt = time.Now()
		s.UpdatedAt = time.Now()

		if err := os.MkdirAll(skillDir, 0755); err != nil {
			return err
		}

		content := renderSkill(&s)
		if err := os.WriteFile(skillPath, []byte(content), 0644); err != nil {
			return err
		}
	}

	return nil
}
