"""
Central Configuration for Atomizer

This file contains all system-level paths and settings.
To update NX version or paths, ONLY modify this file.
"""

from pathlib import Path
import os

# ============================================================================
# NX/SIMCENTER CONFIGURATION
# ============================================================================

# NX Installation Directory
# Change this to update NX version across entire Atomizer codebase
NX_VERSION = "2512"
NX_INSTALLATION_DIR = Path("C:/Program Files/Siemens/DesigncenterNX2512")

# Derived NX Paths (automatically updated when NX_VERSION changes)
NX_BIN_DIR = NX_INSTALLATION_DIR / "NXBIN"
NX_RUN_JOURNAL = NX_BIN_DIR / "run_journal.exe"
NX_MATERIALS_DIR = NX_INSTALLATION_DIR / "UGII" / "materials"
NX_MATERIAL_LIBRARY = NX_MATERIALS_DIR / "physicalmateriallibrary.xml"
NX_PYTHON_STUBS = NX_INSTALLATION_DIR / "ugopen" / "pythonStubs"

# Validate NX installation on import
if not NX_INSTALLATION_DIR.exists():
    raise FileNotFoundError(
        f"NX installation not found at: {NX_INSTALLATION_DIR}\n"
        f"Please update NX_VERSION or NX_INSTALLATION_DIR in config.py"
    )

if not NX_RUN_JOURNAL.exists():
    raise FileNotFoundError(
        f"run_journal.exe not found at: {NX_RUN_JOURNAL}\n"
        f"Please verify NX installation or update paths in config.py"
    )

# ============================================================================
# PYTHON ENVIRONMENT CONFIGURATION
# ============================================================================

# Python Environment Name
PYTHON_ENV_NAME = "atomizer"

# Anaconda/Conda base path (auto-detected from current interpreter)
CONDA_BASE = Path(os.environ.get("CONDA_PREFIX", "")).parent
PYTHON_ENV_PATH = CONDA_BASE / "envs" / PYTHON_ENV_NAME / "python.exe"

# ============================================================================
# PROJECT PATHS
# ============================================================================

# Project root directory
PROJECT_ROOT = Path(__file__).parent.resolve()

# Key directories
OPTIMIZATION_ENGINE_DIR = PROJECT_ROOT / "optimization_engine"
STUDIES_DIR = PROJECT_ROOT / "studies"
DOCS_DIR = PROJECT_ROOT / "docs"
TESTS_DIR = PROJECT_ROOT / "tests"

# ============================================================================
# NASTRAN CONFIGURATION
# ============================================================================

# Nastran solver timeout (seconds)
NASTRAN_TIMEOUT = 600

# Nastran file extensions
NASTRAN_INPUT_EXT = ".dat"
NASTRAN_OUTPUT_EXT = ".op2"
NASTRAN_TEXT_OUTPUT_EXT = ".f06"

# ============================================================================
# OPTIMIZATION DEFAULTS
# ============================================================================

# Default optimization parameters
DEFAULT_N_TRIALS = 50
DEFAULT_TIMEOUT = 3600  # 1 hour
DEFAULT_N_STARTUP_TRIALS = 10

# Optuna sampler settings
DEFAULT_SAMPLER = "TPESampler"
DEFAULT_SURROGATE = "gp"  # gaussian process

# ============================================================================
# LOGGING CONFIGURATION
# ============================================================================

LOG_LEVEL = "INFO"
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

# ============================================================================
# DASHBOARD CONFIGURATION
# ============================================================================

DASHBOARD_HOST = "localhost"
DASHBOARD_PORT = 8050

# ============================================================================
# HELPER FUNCTIONS
# ============================================================================

def get_nx_journal_command(journal_script: Path, *args) -> str:
    """
    Generate NX journal execution command.

    Args:
        journal_script: Path to journal .py file
        *args: Additional arguments to pass to journal

    Returns:
        Command string ready for subprocess execution
    """
    cmd_parts = [f'"{NX_RUN_JOURNAL}"', f'"{journal_script}"']
    if args:
        cmd_parts.append("-args")
        cmd_parts.extend([f'"{arg}"' for arg in args])
    return " ".join(cmd_parts)


def validate_config():
    """
    Validate all critical paths exist.
    Raises FileNotFoundError if any critical path is missing.
    """
    critical_paths = {
        "NX Installation": NX_INSTALLATION_DIR,
        "NX run_journal.exe": NX_RUN_JOURNAL,
        "NX Material Library": NX_MATERIAL_LIBRARY,
        "NX Python Stubs": NX_PYTHON_STUBS,
        "Project Root": PROJECT_ROOT,
        "Optimization Engine": OPTIMIZATION_ENGINE_DIR,
    }

    missing = []
    for name, path in critical_paths.items():
        if not path.exists():
            missing.append(f"  - {name}: {path}")

    if missing:
        raise FileNotFoundError(
            "Critical paths missing:\n" + "\n".join(missing) +
            "\n\nPlease update paths in config.py"
        )

    return True


def print_config():
    """Print current configuration for debugging."""
    print("=" * 80)
    print("ATOMIZER CONFIGURATION")
    print("=" * 80)
    print(f"\nNX Configuration:")
    print(f"  Version: {NX_VERSION}")
    print(f"  Installation: {NX_INSTALLATION_DIR}")
    print(f"  run_journal.exe: {NX_RUN_JOURNAL}")
    print(f"  Material Library: {NX_MATERIAL_LIBRARY}")
    print(f"  Python Stubs: {NX_PYTHON_STUBS}")
    print(f"\nPython Environment:")
    print(f"  Environment Name: {PYTHON_ENV_NAME}")
    print(f"  Python Path: {PYTHON_ENV_PATH}")
    print(f"\nProject Paths:")
    print(f"  Root: {PROJECT_ROOT}")
    print(f"  Optimization Engine: {OPTIMIZATION_ENGINE_DIR}")
    print(f"  Studies: {STUDIES_DIR}")
    print("=" * 80)


# Validate configuration on import
validate_config()


# ============================================================================
# USAGE EXAMPLE
# ============================================================================

if __name__ == "__main__":
    # Print configuration
    print_config()

    # Example: Generate journal command
    example_journal = PROJECT_ROOT / "optimization_engine" / "import_expressions.py"
    example_prt = PROJECT_ROOT / "studies" / "beam" / "Beam.prt"
    example_exp = PROJECT_ROOT / "studies" / "beam" / "Beam_vars.exp"

    cmd = get_nx_journal_command(example_journal, example_prt, example_exp)
    print(f"\nExample Journal Command:\n{cmd}")
