"""Persona loader with Ojas integration.

Loads base persona from config/personas/archetypes/ and optionally merges
Ojas data (traits, virtues, dimensions, allies by team/tier).

Saturn Wave 6.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any

import yaml


def _get_config_root() -> Path:
    return Path(__file__).resolve().parents[2]


def _config_dir() -> Path:
    from vastian.storage.data_root import get_config_dir

    return get_config_dir(_get_config_root())


def _load_yaml(path: Path) -> list | dict | None:
    if not path.exists():
        return None
    try:
        return yaml.safe_load(path.read_text(encoding="utf-8"))
    except Exception:
        return None


def _load_persona_base(persona_id: str | int) -> dict | None:
    """Load base persona from archetypes (persona_1..12)."""
    arcdir = _config_dir() / "personas" / "archetypes"
    if not arcdir.exists():
        return None
    pid_str = str(persona_id)
    for f in arcdir.glob("*.yaml"):
        data = _load_yaml(f)
        if data and (
            str(data.get("persona_id")) == pid_str
            or pid_str.lower() in str(data.get("name", "")).lower()
        ):
            return dict(data)
    return None


def _resolve_allies_from_ojas(team_id: int, tier: int = 1) -> list[dict]:
    """Load allies from ojas/allies.yaml filtered by team_id and tier."""
    allies_path = _config_dir() / "personas" / "ojas" / "allies.yaml"
    allies_data = _load_yaml(allies_path)
    if not isinstance(allies_data, list):
        return []
    return [
        dict(a)
        for a in allies_data
        if isinstance(a, dict) and a.get("team_id") == team_id and a.get("tier", 1) == tier
    ]


def load_persona_config(
    persona_id: str | int,
    *,
    include_ojas: bool = True,
    team_id: int | None = None,
    tier: int = 1,
    trait_overrides: dict[str, float] | None = None,
) -> dict[str, Any] | None:
    """
    Load persona config with optional Ojas augmentation.

    - include_ojas: when True, load ojas traits/virtues/dimensions
    - team_id, tier: when set, resolve allies from ojas for that team/tier
    - trait_overrides: optional dict of trait_name -> score to override default_scores
    """
    base = _load_persona_base(persona_id)
    if not base:
        return None

    result = dict(base)

    if trait_overrides:
        ds = result.get("default_scores") or {}
        if not isinstance(ds, dict):
            ds = {}
        # Map trait names to indices if we have persona_traits
        traits_path = _config_dir() / "personas" / "persona_traits.yaml"
        traits_list = _load_yaml(traits_path)
        if isinstance(traits_list, list):
            name_to_id = {}
            for t in traits_list:
                if isinstance(t, dict) and (t.get("trait_id") or t.get("id")) and t.get("name"):
                    tid = t.get("trait_id") or t.get("id")
                    name_to_id[str(t["name"]).lower()] = tid
            for name, score in trait_overrides.items():
                tid = name_to_id.get(str(name).lower())
                if tid is not None:
                    ds[tid] = float(score)
        result["default_scores"] = ds

    if include_ojas:
        ojas_dir = _config_dir() / "personas" / "ojas"
        if ojas_dir.exists():
            for name in ("traits", "virtues", "dimensions"):
                data = _load_yaml(ojas_dir / f"{name}.yaml")
                if data is not None:
                    result[f"ojas_{name}"] = data

    if team_id is not None:
        allies = _resolve_allies_from_ojas(int(team_id), tier)
        if allies:
            result["allies"] = allies
            result["ojas_team_id"] = team_id
            result["ojas_tier"] = tier

    return result
