"""
cortex/integrations/openclaw_config.py — Config bridge: OpenClaw → CortexConfig.

Maps the OpenClaw memory config section (from ~/.openclaw/openclaw.json)
into a CortexConfig instance that CortexPlugin understands.

OpenClaw config shape (memory section of openclaw.json):
    {
        "backend": "cortex",
        "cortex": {
            "db_path": "~/.openclaw/cortex.db",
            "config_path": "~/.openclaw/cortex.toml",
            "owner_id": "eva",
            "auto_sleep_on_session_end": true,
            "cornerstone_injection": true
        }
    }

Dependencies: cortex.config.CortexConfig
Used by: cortex.integrations.openclaw_plugin
"""
from __future__ import annotations

import os
from pathlib import Path
from typing import Any, Dict, Optional


def resolve_path(raw: str) -> str:
    """Expand ~ and env vars, return absolute path string."""
    return str(Path(os.path.expandvars(os.path.expanduser(raw))).resolve())


def openclaw_config_to_cortex(
    openclaw_memory_config: Dict[str, Any],
) -> tuple:
    """Convert OpenClaw memory config dict → (CortexConfig kwargs, extra_opts).

    Returns:
        (config_kwargs, extra_opts) where:
        - config_kwargs: dict suitable for CortexConfig(**kwargs) or from_toml()
        - extra_opts: OpenClaw-specific options not in CortexConfig
            {
                "auto_sleep_on_session_end": bool,
                "cornerstone_injection": bool,
            }
    """
    cortex_section = openclaw_memory_config.get("cortex", {})

    # --- Paths ---
    db_path = cortex_section.get("db_path", "~/.openclaw/cortex.db")
    config_path = cortex_section.get("config_path")

    # --- CortexConfig-compatible kwargs ---
    config_kwargs: Dict[str, Any] = {
        "storage_db_path": resolve_path(db_path),
        "owner_id": cortex_section.get("owner_id", "default"),
    }

    # --- Extra OpenClaw-specific options ---
    extra_opts = {
        "auto_sleep_on_session_end": cortex_section.get(
            "auto_sleep_on_session_end", True
        ),
        "cornerstone_injection": cortex_section.get("cornerstone_injection", True),
        "config_path": resolve_path(config_path) if config_path else None,
    }

    return config_kwargs, extra_opts


def build_cortex_config(
    openclaw_memory_config: Dict[str, Any],
):
    """Build a CortexConfig from OpenClaw memory config.

    If a cortex TOML config_path is specified and exists, loads from that
    file first, then overlays OpenClaw-specific settings.

    Returns:
        (CortexConfig, extra_opts)
    """
    from cortex.config import CortexConfig

    config_kwargs, extra_opts = openclaw_config_to_cortex(openclaw_memory_config)
    toml_path = extra_opts.get("config_path")

    if toml_path and Path(toml_path).is_file():
        config = CortexConfig.from_toml(toml_path)
        # Overlay OpenClaw-specific fields
        config.storage_db_path = config_kwargs["storage_db_path"]
        config.owner_id = config_kwargs["owner_id"]
    else:
        config = CortexConfig(**config_kwargs)

    return config, extra_opts
