import shutil
from datetime import UTC, datetime
from pathlib import Path

import logging

from .config_parser import ConfigEntryType
from .file_operations import ensure_dir

logger = logging.getLogger(__name__)

STATE_ROOT = Path("/var/lib/tuxedo-tomte/state")
INSTALLED_DIR = STATE_ROOT / "installed"


def ensure_installed_state_dirs() -> None:
    """Create the state layout used for package and script install markers."""
    ensure_dir(INSTALLED_DIR / ConfigEntryType.PKG)
    ensure_dir(INSTALLED_DIR / ConfigEntryType.SCRIPT)


def mark_installed(pkg: str, config_type: ConfigEntryType) -> bool:
    """
    Mark a package or script as installed by creating a timestamped flag file.
    """
    logger.debug(f"Marking {config_type} as installed: {pkg}")

    ensure_dir(INSTALLED_DIR / config_type)

    flag_file = INSTALLED_DIR / config_type / pkg
    timestamp = datetime.now(UTC).isoformat()

    try:
        flag_file.write_text(timestamp + "\n", encoding="utf-8")
        logger.info(f"Created install flag: {flag_file}")
    except Exception as e:
        logger.error(f"Failed to write install flag {flag_file}: {e}")
        return False
    return True


def is_already_installed(pkg: str, config_type: ConfigEntryType) -> bool:
    """
    Returns True if the flag file exists.
    """

    flag_file = INSTALLED_DIR / config_type / pkg
    exists = flag_file.exists()

    logger.debug(f"Check installed: {pkg} -> {exists}")

    return exists


def reset_installed_state() -> bool:
    """
    Removes all installation flags.
    """

    if not INSTALLED_DIR.exists():
        logger.info("No installed-state directory present. Nothing to reset.")
        return True

    logger.info("Resetting installed package state flags...")

    for entry in INSTALLED_DIR.iterdir():
        try:
            if entry.is_dir() and not entry.is_symlink():
                shutil.rmtree(entry)
            else:
                entry.unlink()

            logger.debug(f"Removed: {entry}")

        except Exception as e:
            logger.error(f"Could not remove {entry}: {e}")
            return False

    return True
