"""
Directory setup and software file copying module.
"""

import logging
import os
from pathlib import Path
import shutil
from typing import Optional

from module.config import InstallerConfig, detect_target_drive

logger = logging.getLogger("acc_installer")


def setup_directories_and_copy(config: Optional[InstallerConfig] = None) -> Path:
    """
    Create directories on the target drive and copy software packages from source.
    """
    if config is None:
        config = InstallerConfig()

    print(f"[+] Selected target drive: {config.target_drive}")
    print(f"[+] Target base directory: {config.base_dir}")

    # Ensure source directory exists
    source_dir = Path(config.source_dir)
    if not source_dir.exists():
        raise FileNotFoundError(f"Source directory does not exist: {source_dir}")

    # Create destination directories
    config.ensure_directories()
    print(f"  [+] Target directories ready at {config.soft_dir}")

    print(f"[+] Copying files from {source_dir} to {config.soft_dir} ...")

    if config.dry_run:
        items = list(source_dir.iterdir())
        print(f"  [DRY-RUN] Would copy {len(items)} items from {source_dir} to {config.soft_dir}")
        return config.soft_dir

    copied_count = 0
    for item in source_dir.iterdir():
        dest = config.soft_dir / item.name
        if item.is_dir():
            shutil.copytree(item, dest, dirs_exist_ok=True)
        else:
            shutil.copy2(item, dest)
        copied_count += 1

    print(f"  [+] {copied_count} file(s)/folder(s) copied successfully to {config.soft_dir}.")
    return config.soft_dir


if __name__ == "__main__":
    import sys
    logging.basicConfig(level=logging.INFO, format="%(message)s")
    print("[*] Running directory setup and copier module standalone ...")
    try:
        cfg = InstallerConfig(target_drive=detect_target_drive())
        setup_directories_and_copy(cfg)
        print("[+] Directory copier module completed successfully.")
    except Exception as e:
        print(f"[-] Error: {e}", file=sys.stderr)
        sys.exit(1)
