"""
Init command - Create a new project structure
"""

import sys
from pathlib import Path
from typing import Optional

from infoman.cli.scaffold import ProjectScaffold


def init_project(project_name: Optional[str] = None, target_dir: Optional[str] = None) -> int:
    """
    Initialize a new project with standard structure

    Args:
        project_name: Name of the project (optional, will prompt if not provided)
        target_dir: Target directory (optional, defaults to current directory)

    Returns:
        Exit code (0 for success, 1 for error)
    """
    # Get project name from argument or prompt
    if not project_name:
        try:
            project_name = input("Enter project name: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nOperation cancelled.")
            return 1

    if not project_name:
        print("Error: Project name cannot be empty")
        return 1

    # Validate project name
    if not project_name.replace("-", "").replace("_", "").isalnum():
        print("Error: Project name can only contain letters, numbers, hyphens, and underscores")
        return 1

    # Parse target directory
    target_path = Path(target_dir) / project_name if target_dir else None

    try:
        # Create scaffold generator
        scaffold = ProjectScaffold(project_name, target_path)

        # Generate project structure
        scaffold.generate()

        return 0

    except FileExistsError as e:
        print(f"Error: {e}")
        print("Please choose a different project name or remove the existing directory.")
        return 1

    except PermissionError as e:
        print(f"Error: Permission denied - {e}")
        return 1

    except Exception as e:
        print(f"Error: Failed to create project - {e}")
        return 1


def main() -> None:
    """Main entry point for CLI"""
    import argparse

    parser = argparse.ArgumentParser(
        description="Infoman CLI - Project scaffolding tool",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  infomancli init                    # Interactive mode
  infomancli init my-project         # Create project named 'my-project'
  infomancli init my-app --dir /tmp  # Create in specific directory

For more information, visit: https://github.com/infoman-lib/infoman-pykit
        """,
    )

    parser.add_argument(
        "command",
        choices=["init"],
        help="Command to execute",
    )

    parser.add_argument(
        "project_name",
        nargs="?",
        help="Name of the project to create",
    )

    parser.add_argument(
        "--dir",
        "-d",
        dest="target_dir",
        help="Target directory (default: current directory)",
    )

    parser.add_argument(
        "--version",
        "-v",
        action="version",
        version="infomancli 0.3.1",
    )

    args = parser.parse_args()

    if args.command == "init":
        exit_code = init_project(args.project_name, args.target_dir)
        sys.exit(exit_code)


if __name__ == "__main__":
    main()
