"""
CLI New Project - Create new MDL projects with templates
"""

import os
import shutil
from pathlib import Path
from typing import Optional

from .cli_utils import _slugify


def create_new_project(project_name: str, pack_name: str = None, pack_format: int = 82) -> None:
    """Create a new MDL project with template files."""
    # Validate project name
    if not project_name or not project_name.strip():
        raise ValueError("Project name cannot be empty")
    
    # Clean and validate project name
    clean_name = _slugify(project_name.strip())
    if not clean_name:
        raise ValueError("Project name must contain valid characters")
    
    # Use pack_name if provided, otherwise use project name
    if pack_name is None:
        pack_name = project_name
    
    # Validate pack format
    if not isinstance(pack_format, int) or pack_format < 1:
        raise ValueError("Pack format must be a positive integer")
    
    # Create project directory
    project_dir = Path(clean_name)
    if project_dir.exists():
        raise ValueError(f"Project directory '{clean_name}' already exists")
    
    try:
        # Create the project directory
        project_dir.mkdir(parents=True, exist_ok=False)
        
        # Create the main MDL file
        mdl_file = project_dir / f"{clean_name}.mdl"
        
        # Generate template content
        template_content = _generate_mdl_template(clean_name, pack_name, pack_format)
        
        with open(mdl_file, 'w', encoding='utf-8') as f:
            f.write(template_content)
        
        # Create README.md
        readme_content = _generate_readme_template(clean_name, pack_name)
        readme_file = project_dir / "README.md"
        
        with open(readme_file, 'w', encoding='utf-8') as f:
            f.write(readme_content)
        
        print(f"✅ Successfully created new MDL project: {clean_name}")
        print(f"📁 Project directory: {project_dir.absolute()}")
        print(f"📄 Main file: {mdl_file}")
        print(f"📖 Documentation: {readme_file}")
        print()
        print("🚀 Next steps:")
        print(f"  1. cd {clean_name}")
        print(f"  2. Edit {clean_name}.mdl with your code")
        print(f"  3. mdl build --mdl {clean_name}.mdl -o dist")
        print(f"  4. mdl check {clean_name}.mdl")
        print()
        print("📚 Learn more:")
        print("   • Language Reference: https://mdl-lang.com/docs/language-reference")
        print("   • Examples: https://mdl-lang.com/docs/examples")
        print("   • CLI Reference: https://mdl-lang.com/docs/cli-reference")
    
    except Exception as e:
        # Clean up on error
        if project_dir.exists():
            shutil.rmtree(project_dir)
        raise ValueError(f"Failed to create project: {str(e)}")


def _generate_mdl_template(project_name: str, pack_name: str, pack_format: int) -> str:
    """Generate the template MDL content."""
    return f'''pack {{
  name: "{pack_name}"
  format: {pack_format}
  description: "Generated by MDL CLI"
}}

// Example variables
variable score = 0
variable lives = 3

// Main function - this runs when called
function main {{
  say "Hello from {project_name}!"
  
  // Set initial values
  score = 10
  lives = 3
  
  // Display current values
  say "Score: $score$"
  say "Lives: $lives$"
  
  // Example conditional statement
  if (score > 5) {{
    say "Great score!"
  }} else {{
    say "Keep trying!"
  }}
  
  // Example while loop
  while (lives > 0) {{
    say "You have $lives$ lives remaining"
    lives = lives - 1
  }}
  
  say "Game over!"
}}

// Load function - this runs when the datapack loads
function load {{
  say "🎮 {pack_name} loaded successfully!"
  say "Type: /function {project_name}:main"
}}

// Tick function - this runs every tick (20 times per second)
function tick {{
  // Add your tick logic here
  // Be careful with performance!
}}

// Example function with parameters
function greet_player {{
  say "Welcome to {pack_name}!"
  say "Have fun playing!"
}}

// Raw Minecraft commands example
$!raw
# You can use raw Minecraft commands here
# These are passed through directly to the output
# Useful for complex commands or commands not yet supported by MDL
tellraw @a {{"text":"Raw command example","color":"gold"}}
raw!$

// Example recipe (optional)
recipe diamond_sword {{
  "type": "minecraft:crafting_shaped",
  "pattern": [
    " D ",
    " D ",
    " S "
  ],
  "key": {{
    "D": {{"item": "minecraft:diamond"}},
    "S": {{"item": "minecraft:stick"}}
  }},
  "result": {{
    "item": "minecraft:diamond_sword",
    "count": 1
  }}
}}

// Example loot table (optional)
loot_table chest_loot {{
  "type": "minecraft:chest",
  "pools": [
    {{
      "rolls": 1,
      "entries": [
        {{
          "type": "minecraft:item",
          "name": "minecraft:diamond",
          "functions": [
            {{
              "function": "minecraft:set_count",
              "count": {{
                "min": 1,
                "max": 3
              }}
            }}
          ]
        }}
      ]
    }}
  ]
}}

// Example advancement (optional)
advancement first_diamond {{
  "display": {{
    "icon": {{
      "item": "minecraft:diamond"
    }},
    "title": {{
      "text": "First Diamond!"
    }},
    "description": {{
      "text": "Find your first diamond"
    }},
    "frame": "task",
    "show_toast": true,
    "announce_to_chat": true,
    "hidden": false
  }},
  "criteria": {{
    "requirement": {{
      "trigger": "minecraft:inventory_changed",
      "conditions": {{
        "items": [
          {{
            "item": "minecraft:diamond"
          }}
        ]
      }}
    }}
  }}
}}
'''


def _generate_readme_template(project_name: str, pack_name: str) -> str:
    """Generate the README template content."""
    return f'''# {pack_name}

A Minecraft datapack created with MDL (Minecraft Datapack Language).

## 🎮 About

This datapack was generated using the MDL CLI tool. MDL is a simplified language for creating Minecraft datapacks with variables, control structures, and easy syntax.

## 📁 Project Structure

```
{project_name}/
├── README.md              # This file
└── {project_name}.mdl    # Main MDL source file
```

## 🚀 Getting Started

### Prerequisites

- Minecraft Java Edition (1.20+ recommended)
- MDL CLI tool installed (`pipx install minecraft-datapack-language`)

### Building the Datapack

1. **Build the project:**
   ```bash
   mdl build --mdl {project_name}.mdl -o dist
   ```

2. **Check for errors:**
   ```bash
   mdl check {project_name}.mdl
   ```

3. **Install in Minecraft:**
   - Copy the `dist` folder to your world's `datapacks` directory
   - Or use the `--wrapper` option to create a zip file:
     ```bash
     mdl build --mdl {project_name}.mdl -o dist --wrapper {project_name}
     ```

### Using the Datapack

1. Load your world in Minecraft
2. The datapack will automatically load
3. Run the main function: `/function {project_name}:main`

## 🔧 Development

### Editing the Code

Open `{project_name}.mdl` in your favorite text editor. The file contains:

- **Pack declaration** - Datapack metadata
- **Variables** - Scoreboard variables for storing data
- **Functions** - The main logic of your datapack
- **Control structures** - If/else statements and loops
- **Raw commands** - Direct Minecraft commands when needed

### Key Features

- **Variables**: Use `variable name = value` to create scoreboard objectives
- **Functions**: Define reusable code blocks with `function name { ... }`
- **Conditionals**: Use `if (condition) { ... } else { ... }`
- **Loops**: Use `while (condition) { ... }` for repeating actions
- **Variable substitution**: Use `$variable$` in commands to insert values

### Example Code

```mdl
// Set a variable
score = 10

// Use it in a command
say "Your score is: $score$"

// Conditional logic
if (score > 5) {{
  say "Great job!"
}} else {{
  say "Keep trying!"
}}
```

## 📚 Resources

- **Language Reference**: https://mdl-lang.com/docs/language-reference
- **CLI Reference**: https://mdl-lang.com/docs/cli-reference
- **Examples**: https://mdl-lang.com/docs/examples
- **GitHub**: https://github.com/aaron777collins/MinecraftDatapackLanguage

## 🐛 Troubleshooting

### Common Issues

1. **"No .mdl files found"**
   - Make sure you're in the correct directory
   - Check that the file has a `.mdl` extension

2. **Syntax errors**
   - Use `mdl check {project_name}.mdl` to find and fix errors
   - Check the error messages for line numbers and suggestions

3. **Datapack not loading**
   - Verify the pack format is correct for your Minecraft version
   - Check that the `dist` folder is in the right location

### Getting Help

- Check the error messages - they include helpful suggestions
- Visit the documentation: https://mdl-lang.com/docs
- Report bugs: https://github.com/aaron777collins/MinecraftDatapackLanguage/issues

## 📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

---

Happy coding! 🎮
'''
