"""CLI for kodx init command."""

import os
import shutil
import sys
import tomllib
from pathlib import Path
from typing import Optional

import typer
from llmproc.cli.log_utils import get_logger

try:
    import llmproc

    LLMPROC_VERSION = llmproc.__version__
except (ImportError, AttributeError):
    LLMPROC_VERSION = "unknown"

from . import __version__ as kodx_version


def get_builtin_programs_dir() -> Path:
    """Get the directory containing built-in program files."""
    return Path(__file__).parent / "programs"


def create_kodx_config(kodx_dir: Path) -> None:
    """Create the .kodx/config.toml file."""
    config_content = f"""# Kodx repository configuration
# Generated by kodx init

[version]
kodx = "{kodx_version}"
llmproc = "{LLMPROC_VERSION}"

# Global defaults (apply to all commands unless overridden)
[global]
# cost_limit = 1.0
# log_level = "INFO"

[ask]
program = ".kodx/ask.yaml"
# cost_limit = 0.5      # Override global for analysis
# log_level = "DEBUG"   # Override global for debugging

[code]
program = ".kodx/code.yaml"
# cost_limit = 2.0      # Override global for implementation
# log_level = "INFO"    # Override global for normal logging
"""

    config_file = kodx_dir / "config.toml"
    config_file.write_text(config_content)


def copy_builtin_programs(kodx_dir: Path) -> None:
    """Copy built-in program files to .kodx directory."""
    builtin_dir = get_builtin_programs_dir()

    for program_name in ["ask", "code"]:
        src_file = builtin_dir / f"{program_name}.yaml"
        dst_file = kodx_dir / f"{program_name}.yaml"

        if not src_file.exists():
            raise FileNotFoundError(f"Built-in program not found: {src_file}")

        shutil.copy2(src_file, dst_file)


def init():
    """Initialize kodx configuration in your git repo."""
    logger = get_logger("INFO")

    # Check if we're in a directory (not necessarily git repo)
    cwd = Path.cwd()
    kodx_dir = cwd / ".kodx"

    # Check if .kodx already exists
    if kodx_dir.exists():
        logger.error(f".kodx directory already exists at {kodx_dir}")
        logger.info("Use 'rm -rf .kodx' to remove existing configuration")
        sys.exit(1)

    try:
        # Create .kodx directory
        kodx_dir.mkdir()
        logger.info(f"Created .kodx directory at {kodx_dir}")

        # Create config.toml
        create_kodx_config(kodx_dir)
        logger.info("Created config.toml")

        # Copy built-in programs
        copy_builtin_programs(kodx_dir)
        logger.info("Copied built-in programs (ask.yaml, code.yaml)")

        # Success message
        typer.echo("✅ kodx initialized successfully!")
        typer.echo("📁 Configuration created in .kodx/")
        typer.echo("📝 Edit .kodx/ask.yaml and .kodx/code.yaml to customize behavior")
        typer.echo("🔧 Modify .kodx/config.toml to point to different programs")

    except Exception as e:
        # Cleanup on failure
        if kodx_dir.exists():
            shutil.rmtree(kodx_dir)
        logger.error(f"Failed to initialize kodx configuration: {e}")
        sys.exit(1)


if __name__ == "__main__":
    init()
