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 main_dir() -> Path:
        # Frozen (Nuitka, PyInstaller, cx_Freeze)
        if getattr(sys, "frozen", False):
            # Prefer argv[0] so Nuitka onefile resolves to the real exe location
            return Path(sys.argv[0]).resolve().parent

        # Source run (script or `python -m pkg`)
        main_mod = sys.modules.get("__main__")
        if main_mod and getattr(main_mod, "__file__", None):
            return Path(main_mod.__file__).resolve().parent

        # Fallback (REPL, unusual launchers)
        return Path.cwd()

    # Permanently switch CWD to the main entry directory
    os.chdir(main_dir())

    if config_paths:
        Config().reload(config_paths)

    return Config().get()
