import click
import subprocess
import shutil
from pathlib import Path
from .config_parser import CppProjectConfig

@click.group()
def cli():
    pass

@cli.command()
def init():
    config_file = Path.cwd() / "cpp.proj"
    if config_file.exists():
        click.echo("cpp.proj already exists")
        return

    CppProjectConfig.create_default('cpp.proj')
    click.echo("Created cpp.proj configuration")
    click.echo("Created include/ directory")
    click.echo("Created plugins/ directory")

@cli.command()
@click.option('--clean', is_flag=True, help='Clean build artifacts first')
@click.option('--verbose', is_flag=True, help='Verbose output')
def rebuild(clean, verbose):
    from ..core.build_manager import BuildManager

    project_root = Path.cwd()
    config = CppProjectConfig()

    compiler = detect_compiler()
    build_dir = config.get_build_dir(compiler)

    if clean and build_dir.exists():
        shutil.rmtree(build_dir)

    build_dir.mkdir(parents=True, exist_ok=True)
    config.update_base_dir(build_dir)

    click.echo(f"Build directory: {build_dir}")
    click.echo("Building C++ modules...")

    try:
        builder = BuildManager(project_root, build_dir, config)
        builder.rebuild_all(verbose=verbose)
        click.echo("\nBuild completed successfully!")
    except Exception as e:
        click.echo(f"\nBuild failed: {e}", err=True)
        raise click.Abort()

@cli.command()
@click.argument('module_name')
def add(module_name):
    plugins_dir = Path("plugins")
    if not plugins_dir.exists():
        click.echo("Error: plugins/ directory not found")
        return

    cp_file = plugins_dir / f"{module_name}.cp"
    if cp_file.exists():
        click.echo(f"Module {module_name} already exists")
        return

    template = f"""SOURCE(include/{module_name}.cpp) && HEADER(include/{module_name}.h) {module_name}

PUBLIC(
    ALL
)
"""

    with open(cp_file, 'w') as f:
        f.write(template)

    click.echo(f"Created {cp_file}")
    click.echo(f"Now create include/{module_name}.cpp and include/{module_name}.h")

def detect_compiler():
    for compiler in ['g++', 'clang++', 'cl']:
        if shutil.which(compiler):
            return compiler.replace('++', '').replace('cl', 'msvc')
    return 'gcc'

if __name__ == '__main__':
    cli()
