"""
Configuration and environment resolution for Acc Installer.
"""

from dataclasses import dataclass, field
import logging
import os
from pathlib import Path
from typing import List, Optional

logger = logging.getLogger("acc_installer")


def detect_target_drive(candidates: Optional[List[str]] = None) -> str:
    """
    Find the first available non-system drive on Windows.
    Falls back to 'C:\\' if no secondary drive is found.
    """
    if candidates is None:
        candidates = ["D", "E", "F", "G", "H"]

    for letter in candidates:
        drive_path = f"{letter}:\\"
        if os.path.exists(drive_path):
            logger.info("Found candidate drive: %s", drive_path)
            return drive_path

    logger.warning("No secondary drive found in candidates. Falling back to C:\\")
    return "C:\\"


@dataclass
class InstallerConfig:
    """
    Centralized configuration holding paths and operational flags for the installer.
    """
    source_dir: Path = field(default_factory=lambda: Path(r"C:\SoftwareNP"))
    target_drive: str = field(default_factory=detect_target_drive)
    dry_run: bool = False
    
    # Calculated paths
    base_dir: Path = field(init=False)
    soft_dir: Path = field(init=False)
    acc_dir: Path = field(init=False)

    def __post_init__(self):
        # Normalize target drive
        if not self.target_drive.endswith("\\") and not self.target_drive.endswith("/"):
            self.target_drive = f"{self.target_drive}\\"

        drive_path = Path(self.target_drive)
        self.base_dir = drive_path / "NovinPardazOne"
        self.soft_dir = self.base_dir / "NovinSoft"
        self.acc_dir = self.base_dir / "NovinAcc"

    def ensure_directories(self) -> None:
        """Create necessary target directories if they do not exist."""
        if self.dry_run:
            logger.info("[DRY-RUN] Would create: %s and %s", self.soft_dir, self.acc_dir)
            return

        self.soft_dir.mkdir(parents=True, exist_ok=True)
        self.acc_dir.mkdir(parents=True, exist_ok=True)
        logger.debug("Ensured directories at %s and %s", self.soft_dir, self.acc_dir)
