import logging
import sys
from pathlib import Path

import click

from .builder import ClaudeBuilder
from .bundled_resources import get_bundled_resources
from .validator import ClaudeValidator, ValidationError

__version__ = "1.0.2"

# Configure logging for CLI - only show warnings and errors to end users
logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)


@click.group()
def cli() -> None:
    """AI Forge - Claude Collective Builder."""
    pass


@cli.command()
@click.argument("path", default=".", type=click.Path())
def init(path: str) -> None:
    """Initialize a Claude Collective project with all required files."""
    try:
        output_dir = Path(path).resolve()
        click.echo(f"🚀 Initializing Claude Collective project in {output_dir}")

        # Create output directory if it doesn't exist
        output_dir.mkdir(parents=True, exist_ok=True)

        # Use bundled resources
        with get_bundled_resources() as (snippets_dir, templates_dir):
            builder = ClaudeBuilder(snippets_dir, templates_dir)
            config = builder.create_default_config()
            config.output_base_dir = output_dir

            builder.build_project(config)

            click.echo("✅ Successfully initialized Claude Collective project!")
            click.echo("📁 Generated files:")
            for target in config.targets:
                file_path = config.output_base_dir / target.output_path
                if file_path.exists():
                    click.echo(f"  ✓ {file_path.relative_to(output_dir)}")

            click.echo("\n🎉 Your Claude Collective project is ready!")
            click.echo(
                "📖 Check the generated CLAUDE.md file for your workflow instructions."
            )

    except Exception as e:
        error_msg = f"Initialization failed: {e}"
        click.echo(f"❌ {error_msg}", err=True)
        sys.exit(1)


@click.group()
def dev() -> None:
    """Development commands for ai-forge maintainers."""
    pass


@dev.command()
@click.option(
    "--snippets-dir", default="snippets", help="Directory containing snippet files"
)
@click.option(
    "--templates-dir", default="templates", help="Directory containing templates"
)
@click.option("--output", default="output/CLAUDE.md", help="Output file path")
@click.option(
    "--all-targets",
    is_flag=True,
    help="Build all targets (CLAUDE.md, settings.json, hooks)",
)
def build(
    snippets_dir: str, templates_dir: str, output: str, all_targets: bool
) -> None:
    """Build CLAUDE.md from snippets."""
    try:
        logger.info(
            f"Starting build with snippets_dir={snippets_dir}, "
            f"templates_dir={templates_dir}, output={output}"
        )
        builder = ClaudeBuilder(Path(snippets_dir), Path(templates_dir))

        if all_targets:
            # Build all targets using the new system
            config = builder.create_default_config()
            config.output_base_dir = Path(output).parent
            builder.build_project(config)
            click.echo(f"✅ Successfully built all targets in {config.output_base_dir}")
        else:
            # Use existing single-file build for backward compatibility
            builder.build_and_save(Path(output))
            click.echo(f"✅ Successfully built {output}")
    except FileNotFoundError as e:
        error_msg = f"File not found: {e}"
        logger.error(error_msg)
        click.echo(f"❌ Build failed: {error_msg}", err=True)
        sys.exit(1)
    except ValueError as e:
        error_msg = f"Invalid input: {e}"
        logger.error(error_msg)
        click.echo(f"❌ Build failed: {error_msg}", err=True)
        sys.exit(1)
    except Exception as e:
        error_msg = f"Unexpected error: {e}"
        logger.error(error_msg, exc_info=True)
        click.echo(f"❌ Build failed: {error_msg}", err=True)
        sys.exit(1)


@dev.command()
@click.argument("document_path", type=click.Path(exists=True))
def validate(document_path: str) -> None:
    """Validate a CLAUDE.md document."""
    try:
        logger.info(f"Starting validation for document: {document_path}")
        validator = ClaudeValidator(Path(document_path))

        if validator.validate_document():
            click.echo("✅ Document validation passed")
        else:
            click.echo("❌ Document validation failed", err=True)
            sys.exit(1)
    except ValidationError as e:
        error_msg = f"Validation error: {e}"
        logger.error(error_msg)
        click.echo(f"❌ {error_msg}", err=True)
        sys.exit(1)
    except Exception as e:
        error_msg = f"Unexpected error during validation: {e}"
        logger.error(error_msg, exc_info=True)
        click.echo(f"❌ {error_msg}", err=True)
        sys.exit(1)


@dev.command()
@click.option(
    "--snippets-dir", default="snippets", help="Directory containing snippet files"
)
@click.option(
    "--templates-dir", default="templates", help="Directory containing templates"
)
@click.option("--output", default="output/CLAUDE.md", help="Output file path")
def build_and_validate(snippets_dir: str, templates_dir: str, output: str) -> None:
    """Build and validate CLAUDE.md in one step."""
    # Build
    try:
        builder = ClaudeBuilder(Path(snippets_dir), Path(templates_dir))
        builder.build_and_save(Path(output))
        click.echo(f"✅ Successfully built {output}")
    except Exception as e:
        click.echo(f"❌ Build failed: {e}", err=True)
        exit(1)

    # Validate
    validator = ClaudeValidator(Path(output))
    if validator.validate_document():
        click.echo("✅ Document validation passed")
    else:
        click.echo("❌ Document validation failed", err=True)
        exit(1)


# Add the dev command group to the main CLI
cli.add_command(dev)


def main() -> None:
    """Entry point for the `ai-forge` console script."""
    cli()


if __name__ == "__main__":
    main()
