"""
Main initialization module for Synapsis DSAI Agent Rules.

This module provides the core functionality for initializing agent rules by
copying template directories (.agent, .agents, .claude) from the package
into the user's current working directory.

Functions:
    run(): Main entry point for the initialization CLI tool.

Example:
    >>> from dsai_synapsis_agent_init.main import run
    >>> run()  # Copies templates to current directory
"""

import shutil
import sys
from pathlib import Path
from importlib.resources import files

# Tuple of template folder names that will be initialized
FOLDERS_TO_INIT = (".agent", ".agents", ".claude")


def _get_template_path() -> Path:
    """
    Retrieve the path to the package's templates directory.

    Returns:
        Path: Traversable object pointing to the templates folder within
              the installed dsai_synapsis_agent_init package.

    Raises:
        Exception: If package resources cannot be accessed (e.g., not installed).
    """
    return files("dsai_synapsis_agent_init") / "templates"


def _copy_template_folder(source: Path, destination: Path, folder_name: str) -> bool:
    """
    Copy or merge a template folder from source to destination.

    Handles merging (adds missing files if destination exists) and provides
    user-friendly output messages.

    Args:
        source: Path to the source template folder.
        destination: Path where the template should be copied.
        folder_name: Name of the folder being copied (for display).

    Returns:
        bool: True if copy succeeded, False if an error occurred.
    """
    # Check if source exists in templates
    if not source.exists():
        print(f"⚠️  Template {folder_name} tidak ditemukan di dalam package.")
        return False

    # Attempt to copy or merge the template directory
    try:
        shutil.copytree(str(source), str(destination), dirs_exist_ok=True)
        print(f"✅ Berhasil memproses {folder_name}")
        return True
    except (OSError, shutil.Error) as e:
        print(f"❌ Gagal memproses {folder_name}: {e}")
        return False


def run() -> None:
    """
    Initialize Synapsis DSAI Agent Rules in the current working directory.

    This is the main entry point for the uvx CLI tool. It copies predefined
    template directories (.agent, .agents, .claude) from the package
    resources into the current working directory.

    Behavior:
        - Skips any folders that already exist in the destination (idempotent).
        - Prints user-friendly messages indicating success or failure.
        - Exits with status code 1 if critical errors occur (e.g., missing resources).

    Side Effects:
        - Creates directories and copies files in the current working directory.
        - Prints informational and error messages to stdout/stderr.
    """
    print("🚀 [Synapsis DSAI] Initializing agent rules...")

    # Step 1: Get the path to the templates directory
    try:
        template_base = _get_template_path()
    except Exception as e:
        print(f"❌ Error internal: {e}")
        sys.exit(1)
        return
    # Step 2: Get the current working directory
    current_work_dir = Path.cwd()

    # Step 2.5: Check for .git directory (team standard check)
    if not (current_work_dir / ".git").exists():
        print("⚠️  Direktori .git tidak ditemukan. Pastikan Anda menjalankan ini di root repository.")

    # Step 3: Iterate over each template folder and copy it
    for folder_name in FOLDERS_TO_INIT:
        source = template_base / folder_name
        destination = current_work_dir / folder_name
        _copy_template_folder(source, destination, folder_name)

    # Step 4: Print completion message
    print("\n✨ Berhasil! Tim sekarang bisa mulai bekerja dengan standar Agent Skills & Rules DS-AI Synapsis.")


if __name__ == "__main__":
    run()
