"""Init command - Initialize new LAIDA project.

Contract: CNT-T4-CMD-001
Traceability: UC-020
"""

import importlib.resources
import shutil
from pathlib import Path

import click
from rich.console import Console

console = Console()


@click.command("init")
@click.option(
    "--force", "-f",
    is_flag=True,
    help="Overwrite existing LAIDA project structure",
)
@click.option(
    "--path", "-p",
    type=click.Path(exists=False),
    default=".",
    help="Path to initialize project (default: current directory)",
)
def init_command(force: bool, path: str) -> None:
    """Initialize a new LAIDA project.

    Creates the following structure:
    - .laida/ (prompts, templates, config)
    - inputs/ (project_context.yaml)
    - outputs/ (generated artifacts)
    """
    project_path = Path(path).resolve()

    # Check if already initialized
    laida_dir = project_path / ".laida"
    if laida_dir.exists() and not force:
        console.print(
            "[red]Error:[/red] LAIDA project already exists. "
            "Use --force to overwrite."
        )
        raise SystemExit(1)

    # Find the source .laida directory
    # Updated to use importlib for package compatibility
    try:
        source_laida = _get_template_source()
    except FileNotFoundError as e:
        console.print(f"[red]Error:[/red] {e}")
        console.print("Please ensure laida-cli is installed correctly with template data.")
        raise SystemExit(1) from e

    console.print(f"[blue]Initializing LAIDA project at:[/blue] {project_path}")

    # Create directory structure
    _create_directories(project_path)

    # Copy .laida directory
    if laida_dir.exists():
        shutil.rmtree(laida_dir)

    # Copy from the source (package or local) to the target
    shutil.copytree(source_laida, laida_dir, dirs_exist_ok=True)

    # Create project_context.yaml from template
    _create_project_context(project_path)

    # Copy CLAUDE.md for Claude Code integration
    _copy_claude_md(project_path)

    console.print("[green]Success![/green] LAIDA project initialized.")
    console.print("")
    console.print("Next steps:")
    console.print("  1. Edit inputs/project_context.yaml with your project details")
    console.print("  2. Run: laida status")
    console.print("  3. Run: laida run 0 0  (to start Phase 0 Step 0)")


def _get_template_source() -> Path:
    """Find the .laida template directory inside the installed package or local dev.

    Returns:
        Path to source .laida directory

    Raises:
        FileNotFoundError if not found
    """
    # 1. Try finding it inside the installed package (Production Mode)
    # This matches the pyproject.toml force-include=".laida=laida_cli/.laida"
    try:
        # We look inside the 'laida_cli' package
        pkg_files = importlib.resources.files("laida_cli")
        template_dir = pkg_files.joinpath(".laida")

        # Check if it exists and is a directory (typical in standard installs)
        if template_dir.is_dir():
            return Path(str(template_dir))

        # Fallback for zipped packages or different install methods
        with importlib.resources.as_file(template_dir) as p:
            if p.exists():
                return p
    except Exception:
        # Ignore errors here and try local fallback
        pass

    # 2. Fallback: Local Development Environment
    # Assuming code is in src/laida_cli/commands/init.py
    # We look for .laida in the project root (3 levels up from here)
    local_dev_path = Path(__file__).resolve().parent.parent.parent.parent / ".laida"
    if local_dev_path.exists() and (local_dev_path / "config.yaml").exists():
        return local_dev_path

    # Try one level deeper just in case (depending on where run from)
    local_dev_path_alt = Path(__file__).resolve().parent.parent.parent / ".laida"
    if local_dev_path_alt.exists():
        return local_dev_path_alt

    raise FileNotFoundError("Cannot find .laida templates in package resources or local path.")


def _create_directories(project_path: Path) -> None:
    """Create project directory structure.

    Args:
        project_path: Path to project root
    """
    dirs = [
        project_path / "inputs",
        project_path / "outputs",
    ]

    for d in dirs:
        d.mkdir(parents=True, exist_ok=True)


def _create_project_context(project_path: Path) -> None:
    """Create project_context.yaml from template.

    Copies the full project_context_template.yaml (219 lines) to inputs/.
    Also copies the template itself so users can reference it.

    Args:
        project_path: Path to project root
    """
    context_file = project_path / "inputs" / "project_context.yaml"
    template_dest = project_path / "inputs" / "project_context_template.yaml"

    # The real template is in .laida/templates/ (copied from package)
    laida_template = project_path / ".laida" / "templates" / "project_context_template.yaml"

    if laida_template.exists():
        # Copy template to inputs/ for reference
        shutil.copy(laida_template, template_dest)
        # Copy as project_context.yaml for user to edit
        shutil.copy(laida_template, context_file)
    else:
        console.print(
            "[yellow]Warning:[/yellow] project_context_template.yaml not found in package. "
            "Creating minimal template."
        )
        # Minimal fallback (should not happen with proper install)
        context_file.write_text(
            "# LAIDA Project Context - Minimal Template\n"
            "# Run 'pip install laida-cli --upgrade' to get the full template\n\n"
            "project:\n"
            "  name: \"\"\n"
            "  description: \"\"\n"
        )


def _copy_claude_md(project_path: Path) -> None:
    """Copy CLAUDE.md to project for Claude Code integration.

    CLAUDE.md contains instructions for Claude Code on how to execute
    the LAIDA methodology. It's essential for proper methodology execution.

    Args:
        project_path: Path to project root
    """
    dest_file = project_path / "CLAUDE.md"

    # Skip if already exists
    if dest_file.exists():
        return

    # Try finding CLAUDE.md in the installed package
    try:
        pkg_files = importlib.resources.files("laida_cli")
        claude_md = pkg_files.joinpath("CLAUDE.md")

        if hasattr(claude_md, "read_text"):
            content = claude_md.read_text()
            dest_file.write_text(content)
            return

        with importlib.resources.as_file(claude_md) as p:
            if p.exists():
                shutil.copy(p, dest_file)
                return
    except Exception:
        pass

    # Fallback: Local development environment
    local_path = Path(__file__).resolve().parent.parent.parent.parent / "CLAUDE.md"
    if local_path.exists():
        shutil.copy(local_path, dest_file)
        return

    # Alternative local path
    local_path_alt = Path(__file__).resolve().parent.parent.parent / "CLAUDE.md"
    if local_path_alt.exists():
        shutil.copy(local_path_alt, dest_file)
        return

    console.print(
        "[yellow]Warning:[/yellow] CLAUDE.md not found in package. "
        "Claude Code integration may not work optimally."
    )
