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
from contextlib import contextmanager

__all__ = ["parse_config", "write_config"]

@contextmanager
def _temp_chdir(path: Path):
    prev = Path.cwd()
    try:
        os.chdir(path)
        yield
    finally:
        os.chdir(prev)

def parse_config(config_paths: Optional[List[str]] = None) -> SimpleNamespace:
    """
    Retrieve the application configuration, including YAML, JSON, TOML, and .env content.
    Temporarily chdirs to the main entry's directory, then restores the original cwd.
    """
    def main_dir() -> Path:
        # Frozen (Nuitka, PyInstaller, cx_Freeze)
        if getattr(sys, "frozen", False):
            return Path(getattr(sys, "executable", 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: interactive shells, etc.
        return Path.cwd()

    with _temp_chdir(main_dir()):
        if config_paths:
            Config().reload(config_paths)

        cfg = Config().get()

    return cfg
