import os
import sys

from .config_parser import Config
from .config_writer import write_config
from types import SimpleNamespace
from typing import Optional, List
from pathlib import Path

__all__ = ["parse_config", "write_config"]

def parse_config(config_paths: Optional[List[str]] = None) -> SimpleNamespace:
    """Retrieve the application configuration, including YAML, JSON, TOML, and .env content.

    Args:
        config_paths: Optional list of paths to project-specific config files.

    Returns:
        SimpleNamespace: A namespace object with config and env values accessible via dot notation.
    """
    def program_dir() -> Path:
        # When frozen (Nuitka / PyInstaller / cx_Freeze), __file__ may not be reliable.
        if getattr(sys, "frozen", False):
            # With Nuitka, both sys.argv[0] and sys.executable point to the built exe.
            return Path(sys.argv[0]).resolve().parent
        else:
            # When running as a normal script.
            return Path(__file__).resolve().parent

    # Change the working directory to where the script/exe lives.
    os.chdir(program_dir())

    if config_paths:
        Config().reload(config_paths)

    return Config().get()
