"""Setup command for initializing Frappe/ERPNext development environment."""

import click
import sys
from pathlib import Path

from ..utils import (
    Colors, print_info, print_success, print_warning, print_error,
    run_command
)


@click.command()
@click.option('--project-name', 
              help='Name of the project (default: current directory name)')
@click.option('--frappe-version', 
              default='v15.78.1',
              help='Frappe version to install (default: v15.78.1)')
@click.option('--python-path',
              default='python3',
              help='Path to Python executable (default: python3)')
@click.option('--force',
              is_flag=True,
              help='Force setup even if virtual environment exists')
def setup(project_name, frappe_version, python_path, force):
    """Setup Frappe/ERPNext development environment.
    
    This command creates a virtual environment, installs frappe-bench,
    and initializes a new bench with the specified Frappe version.
    """
    # Get the directory where this command is being run
    script_dir = Path.cwd()
    
    # Get project name from current directory if not provided
    if not project_name:
        project_name = script_dir.name
    
    print()
    print(f"{Colors.BLUE}{'=' * 63}{Colors.NC}")
    print(f"{Colors.GREEN}  Frappe/ERPNext Environment Setup{Colors.NC}")
    print(f"{Colors.BLUE}{'=' * 63}{Colors.NC}")
    print()
    print_info(f"Project Name: {project_name}")
    print_info(f"Script Directory: {script_dir}")
    print_info(f"Frappe Version: {frappe_version}")
    print()
    
    # Check if virtual environment already exists
    env_dir = script_dir / "env"
    if env_dir.exists() and not force:
        print_warning("Virtual environment already exists!")
        if not click.confirm("Do you want to continue anyway?"):
            print_info("Setup cancelled.")
            return
    
    # ═══════════════════════════════════════════════════════════
    # CREATE VIRTUAL ENVIRONMENT
    # ═══════════════════════════════════════════════════════════
    print_info("Setting up virtual environment...")
    
    if not run_command(f'{python_path} -m venv "{env_dir}"', cwd=script_dir):
        print_error("Failed to create virtual environment!")
        sys.exit(1)
    
    print_success("Virtual environment created")
    print()
    
    # Paths to executables in virtual environment
    python_exe = env_dir / "bin" / "python"
    pip_exe = env_dir / "bin" / "pip"
    
    # ═══════════════════════════════════════════════════════════
    # UPGRADE PIP
    # ═══════════════════════════════════════════════════════════
    print_info("Upgrading pip...")
    if not run_command(f'"{python_exe}" -m pip install --quiet --upgrade pip', 
                      cwd=script_dir, quiet=True):
        print_error("Failed to upgrade pip!")
        sys.exit(1)
    
    print_success("pip upgraded")
    print()
    
    # ═══════════════════════════════════════════════════════════
    # INSTALL FRAPPE-BENCH
    # ═══════════════════════════════════════════════════════════
    print_info("Installing frappe-bench...")
    if not run_command(f'"{python_exe}" -m pip install --quiet frappe-bench', 
                      cwd=script_dir, quiet=True):
        print_error("Failed to install frappe-bench!")
        sys.exit(1)
    
    print_success("frappe-bench installed")
    print()
    
    # ═══════════════════════════════════════════════════════════
    # INSTALL WHEEL
    # ═══════════════════════════════════════════════════════════
    print_info("Installing wheel...")
    if not run_command(f'"{python_exe}" -m pip install --quiet wheel', 
                      cwd=script_dir, quiet=True):
        print_error("Failed to install wheel!")
        sys.exit(1)
    
    print_success("wheel installed")
    print()
    
    # ═══════════════════════════════════════════════════════════
    # INITIALIZE BENCH
    # ═══════════════════════════════════════════════════════════
    print_info("Getting frappe and initializing bench...")
    print_warning("This may take a while...")
    print()
    
    # Change to parent directory to run bench init
    parent_dir = script_dir.parent
    
    # Build bench init command
    bench_cmd = (f'source "{env_dir}/bin/activate" && '
                f'bench init {project_name} --frappe-branch {frappe_version} --ignore-exist')
    
    if not run_command(bench_cmd, cwd=parent_dir, shell=True, check=True, quiet=False):
        print_error("Failed to initialize bench!")
        sys.exit(1)
    
    print()
    print_success("Bench initialized successfully!")
    print()
    
    # ═══════════════════════════════════════════════════════════
    # FINAL MESSAGE
    # ═══════════════════════════════════════════════════════════
    print()
    print(f"{Colors.BLUE}{'=' * 63}{Colors.NC}")
    print(f"{Colors.GREEN}  Setup Completed Successfully!{Colors.NC}")
    print(f"{Colors.BLUE}{'=' * 63}{Colors.NC}")
    print()
    print_success("Your Frappe development environment is ready!")
    print()
    print_info("Next steps:")
    print(f"  1. Activate the virtual environment:")
    print(f"     {Colors.YELLOW}source env/bin/activate{Colors.NC}")
    print(f"  2. Create a new site:")
    print(f"     {Colors.YELLOW}ws-frappe-cli create-site{Colors.NC}")
    print(f"  3. Install apps:")
    print(f"     {Colors.YELLOW}ws-frappe-cli fetch-app{Colors.NC}")
    print(f"  4. Start the development server:")
    print(f"     {Colors.YELLOW}bench start{Colors.NC}")
    print()


if __name__ == "__main__":
    setup()