import logging
import shutil
from pathlib import Path

from .file_operations import ensure_dir
from .migration_classic_tomte import (
    migrate_classic_tomte_fixes,
    CLASSIC_TOMTE_MODULES_CONFIG,
)
from .state_manager import INSTALLED_DIR, ensure_installed_state_dirs

TOMTE_LIGHT_INSTALLED_DIR = Path("/var/lib/tuxedo-tomte-light/state/installed")

logger = logging.getLogger(__name__)


def is_migration_needed() -> bool:
    return CLASSIC_TOMTE_MODULES_CONFIG.exists() or TOMTE_LIGHT_INSTALLED_DIR.is_dir()


def execute_migrations() -> bool:
    """Execute migrations."""
    ensure_installed_state_dirs()

    logger.info("Migrating old flags...")
    legacy_flags_migrated = migrate_legacy_installed_flags()

    logger.info("Migrating classic TUXEDO Tomte fixes...")
    legacy_tomte_migrated = migrate_classic_tomte_fixes()

    return legacy_flags_migrated and legacy_tomte_migrated


def migrate_legacy_installed_flags() -> bool:
    """
    Migrate legacy installed flags.

    Old layout:
        INSTALLED_DIR/<name>

    New layout:
        INSTALLED_DIR/package/<name>
        INSTALLED_DIR/script/<name>
    """
    if not TOMTE_LIGHT_INSTALLED_DIR.is_dir():
        logger.info("No TUXEDO Tomte Light state path found. Nothing to migrate.")
        return True
    logger.debug("Checking for legacy installed flags")

    package_dir = INSTALLED_DIR / "package"
    script_dir = INSTALLED_DIR / "script"

    try:
        ensure_dir(package_dir)
        ensure_dir(script_dir)

        for flag_file in TOMTE_LIGHT_INSTALLED_DIR.iterdir():
            if not flag_file.is_file():
                logger.warning(
                    f"Skipping unexpected entry in installed dir: {flag_file}"
                )
                continue

            target = package_dir / flag_file.name

            if target.exists():
                logger.info(
                    f"Legacy flag already migrated, removing old flag: {flag_file}"
                )
                flag_file.unlink()
                continue

            logger.info(f"Migrating legacy installed flag: {flag_file} -> {target}")
            flag_file.rename(target)
        shutil.rmtree(TOMTE_LIGHT_INSTALLED_DIR)

    except Exception as e:
        logger.error(f"Failed to migrate legacy installed flags: {e}")
        return False

    return True
