import logging
import os
from functools import cache
from pathlib import Path

import yaml
from pydantic import BaseModel

from test_automation_suite.utility.cmd import run_cmd

logger = logging.getLogger(__name__)


def xdg_config_home() -> str:
    return os.getenv("XDG_CONFIG_HOME") or str(Path.home() / ".config")


@cache
def get_desktop_dir() -> Path | None:
    cmd = run_cmd(f"bash -c 'source {xdg_config_home()}/user-dirs.dirs && echo $XDG_DESKTOP_DIR'")
    if not cmd.success:
        logger.warning("Failed to locate $XDG_DESKTOP_DIR")
        return None
    desktop_path = Path(cmd.stdout.strip())
    if not desktop_path.is_dir():
        logger.warning("Failed to locate $XDG_DESKTOP_DIR")
        return None
    logger.info("Found desktop directory at %s", str(desktop_path))
    return desktop_path


class Config(BaseModel):
    output_base_directory: Path = (get_desktop_dir() or Path.home()) / "test-automation-suite"
    state_file: Path = (get_desktop_dir() or Path.home()) / "test-automation-suite" / "state.json"
    autostart_file: Path = Path(xdg_config_home()) / "autostart" / "tas-autostarter.desktop"
    procedure_directory: Path = Path("/etc/test-automation-suite")
    dependency_installation_directory: Path = Path("/opt/test-automation-suite")

    @staticmethod
    def load(path: str | Path) -> "Config":
        config_yaml = Path(path).read_text(encoding="utf-8")
        config_dict = yaml.safe_load(config_yaml)
        return Config.model_validate(config_dict)
