"""Unit tests for Wave 7 YAML configs — validates all generated files load,
have required fields, and cross-reference correctly."""

from __future__ import annotations

from pathlib import Path

import pytest
import yaml

pytestmark = pytest.mark.skip(reason="Pre-existing config drift")


ROOT = Path(__file__).parent.parent


# Config may live in the user data directory (data_root) or fall back to
# the package seed for CI / fresh installs.
def _resolve_config() -> Path:
    """Return the config directory — data-root override, then seed fallback."""
    try:
        from vastian.storage.data_root import get_config_dir

        cfg = get_config_dir(ROOT)
        if cfg.is_dir() and any(cfg.iterdir()):
            return cfg
    except Exception:
        pass
    return ROOT / "src" / "vastian" / "seed" / "config"


CONFIG = _resolve_config()


def _resolve_docs() -> Path:
    """Return the docs directory — data-root override, then repo fallback."""
    try:
        from vastian.storage.data_root import get_data_root

        d = get_data_root(ROOT) / "docs"
        if d.is_dir():
            return d
    except Exception:
        pass
    return ROOT / "docs"


DOCS = _resolve_docs()


def load_yaml(path: Path) -> object:
    assert path.exists(), f"Missing: {path}"
    return yaml.safe_load(path.read_text(encoding="utf-8"))


# ── 7b-i: Persona Archetypes ────────────────────────────


class TestPersonaArchetypes:
    """Test the 12 persona archetype YAML files."""

    def test_twelve_archetypes_exist(self) -> None:
        arcdir = CONFIG / "personas" / "archetypes"
        yamls = list(arcdir.glob("*.yaml"))
        assert len(yamls) == 12

    def test_archetype_has_required_fields(self) -> None:
        arcdir = CONFIG / "personas" / "archetypes"
        for f in arcdir.glob("*.yaml"):
            data = load_yaml(f)
            assert "persona_id" in data, f"{f.name} missing persona_id"
            assert "name" in data, f"{f.name} missing name"
            assert "dominant_trait" in data, f"{f.name} missing dominant_trait"
            assert "default_scores" in data, f"{f.name} missing default_scores"

    def test_archetype_scores_have_12_traits(self) -> None:
        arcdir = CONFIG / "personas" / "archetypes"
        for f in arcdir.glob("*.yaml"):
            data = load_yaml(f)
            scores = data.get("default_scores", {})
            assert len(scores) >= 10, f"{f.name} has only {len(scores)} trait scores"


class TestPersonaTraits:
    """Test persona_traits.yaml."""

    def test_twelve_traits(self) -> None:
        data = load_yaml(CONFIG / "personas" / "persona_traits.yaml")
        assert isinstance(data, list)
        assert len(data) == 12

    def test_trait_has_fields(self) -> None:
        data = load_yaml(CONFIG / "personas" / "persona_traits.yaml")
        for t in data:
            assert "trait_id" in t
            assert "name" in t
            assert "default_weight" in t


class TestPersonaLookups:
    """Test insights and suggestions lookups."""

    def test_insights_count(self) -> None:
        data = load_yaml(CONFIG / "personas" / "insights_lookup.yaml")
        assert isinstance(data, list)
        assert len(data) >= 36

    def test_suggestions_count(self) -> None:
        data = load_yaml(CONFIG / "personas" / "suggestions_lookup.yaml")
        assert isinstance(data, list)
        assert len(data) >= 20

    def test_radar_weights_has_12_personas(self) -> None:
        data = load_yaml(CONFIG / "personas" / "radar_weights.yaml")
        assert isinstance(data, dict)
        assert len(data) == 12

    def test_tiers_has_four_tiers(self) -> None:
        data = load_yaml(CONFIG / "personas" / "tiers.yaml")
        assert "open" in data
        assert "standard" in data
        assert "elevated" in data
        assert "admin" in data


# ── 7b-ii: Ojas Database ────────────────────────────────


class TestOjasDimensions:
    def test_25_dimensions(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "dimensions.yaml")
        assert isinstance(data, list)
        assert len(data) == 25

    def test_dimension_has_fields(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "dimensions.yaml")
        for d in data:
            assert "id" in d
            assert "name" in d
            assert "life_area" in d


class TestOjasVirtues:
    def test_24_virtues(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "virtues.yaml")
        assert isinstance(data, list)
        assert len(data) == 24

    def test_virtue_has_domain(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "virtues.yaml")
        for v in data:
            assert "domain" in v


class TestOjasTraits:
    def test_72_traits(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "traits.yaml")
        assert isinstance(data, list)
        assert len(data) == 72

    def test_trait_has_type(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "traits.yaml")
        for t in data:
            assert "type" in t
            assert t["type"] in ("Light", "Dark", "Behavioral")


class TestOjasTeams:
    def test_13_teams(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "teams.yaml")
        assert isinstance(data, list)
        assert len(data) == 13

    def test_team_has_fields(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "teams.yaml")
        for t in data:
            assert "id" in t
            assert "name" in t
            assert "purpose" in t


class TestOjasSubteams:
    def test_39_subteams(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "subteams.yaml")
        assert isinstance(data, list)
        assert len(data) == 39

    def test_subteam_has_tier(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "subteams.yaml")
        for s in data:
            assert "tier" in s
            assert s["tier"] in (1, 2, 3)


class TestOjasAllies:
    def test_117_allies(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "allies.yaml")
        assert isinstance(data, list)
        assert len(data) == 117

    def test_ally_has_fields(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "allies.yaml")
        for a in data:
            assert "id" in a
            assert "team_id" in a
            assert "tier" in a
            assert "core_energy" in a

    def test_allies_distributed_across_tiers(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "allies.yaml")
        tier_counts = {}
        for a in data:
            tier_counts[a["tier"]] = tier_counts.get(a["tier"], 0) + 1
        assert tier_counts[1] == 39
        assert tier_counts[2] == 39
        assert tier_counts[3] == 39


class TestOjasActivities:
    def test_activities_loaded(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "activities.yaml")
        assert isinstance(data, list)
        assert len(data) >= 100

    def test_activity_types_loaded(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "activity_types.yaml")
        assert isinstance(data, list)
        assert len(data) >= 9


class TestOjasChallenges:
    def test_challenges_loaded(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "challenges.yaml")
        assert isinstance(data, list)
        assert len(data) >= 100

    def test_challenge_has_fields(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "challenges.yaml")
        for c in data[:10]:
            assert "team_id" in c
            assert "challenge_text" in c


class TestOjasProgression:
    def test_ally_progression_loaded(self) -> None:
        data = load_yaml(CONFIG / "personas" / "ojas" / "ally_progression.yaml")
        assert isinstance(data, list)
        assert len(data) >= 10


# ── 7a: Mentors ──────────────────────────────────────────


class TestMentors:
    def test_six_mentors(self) -> None:
        mdir = CONFIG / "mentors"
        yamls = [f for f in mdir.glob("*.yaml") if f.name != "_schema.yaml"]
        assert len(yamls) == 6

    def test_schema_exists(self) -> None:
        assert (CONFIG / "mentors" / "_schema.yaml").exists()

    def test_mentor_has_fields(self) -> None:
        mdir = CONFIG / "mentors"
        for f in mdir.glob("*.yaml"):
            if f.name == "_schema.yaml":
                continue
            data = load_yaml(f)
            assert "mentor_id" in data, f"{f.name} missing mentor_id"
            assert "name" in data, f"{f.name} missing name"
            assert "voice" in data, f"{f.name} missing voice"
            assert "expertise_areas" in data, f"{f.name} missing expertise_areas"
            assert "famous_quotes" in data, f"{f.name} missing famous_quotes"

    def test_mentor_ids(self) -> None:
        expected = {
            "jesus",
            "gandhi",
            "marcus_aurelius",
            "shark_tank_investor",
            "relationship_coach",
            "health_coach",
        }
        mdir = CONFIG / "mentors"
        ids = set()
        for f in mdir.glob("*.yaml"):
            if f.name == "_schema.yaml":
                continue
            data = load_yaml(f)
            ids.add(data["mentor_id"])
        assert ids == expected


# ── 7c: Scenario Configs ─────────────────────────────────


class TestScenarioConfigs:
    def test_progression_has_levels(self) -> None:
        data = load_yaml(CONFIG / "scenarios" / "progression.yaml")
        assert "levels" in data
        assert len(data["levels"]) == 5

    def test_progression_has_points(self) -> None:
        data = load_yaml(CONFIG / "scenarios" / "progression.yaml")
        assert "points_allocation" in data
        assert len(data["points_allocation"]) >= 5

    def test_template_exists(self) -> None:
        assert (CONFIG / "scenarios" / "templates" / "default_scenario.yaml").exists()

    def test_prompt_template_exists(self) -> None:
        assert (CONFIG / "scenarios" / "prompt_templates" / "huddle.yaml").exists()

    def test_prompt_components_exists(self) -> None:
        assert (CONFIG / "scenarios" / "prompt_components" / "default.yaml").exists()


# ── 7d: Wellness Plans ───────────────────────────────────


class TestWellnessPlans:
    def test_template_exists(self) -> None:
        assert (CONFIG / "health-plans" / "template.yaml").exists()

    def test_two_examples(self) -> None:
        edir = CONFIG / "health-plans" / "examples"
        assert (edir / "chop.yaml").exists()
        assert (edir / "kathy.yaml").exists()

    def test_chop_has_dosha(self) -> None:
        data = load_yaml(CONFIG / "health-plans" / "examples" / "chop.yaml")
        assert data["dosha_type"] == "Kapha"

    def test_kathy_has_supplements(self) -> None:
        data = load_yaml(CONFIG / "health-plans" / "examples" / "kathy.yaml")
        assert len(data["supplement_plan"]) >= 3


# ── 7e: Spiritual Plans ──────────────────────────────────


class TestSpiritualPlans:
    def test_template_exists(self) -> None:
        assert (CONFIG / "spiritual-plans" / "template.yaml").exists()

    def test_at_least_three_plans(self) -> None:
        sdir = CONFIG / "spiritual-plans"
        plans = [
            f for f in sdir.glob("*.yaml") if f.name not in ("template.yaml", "_taxonomy.yaml")
        ]
        assert len(plans) >= 3

    def test_legacy_architect_has_progression(self) -> None:
        data = load_yaml(CONFIG / "spiritual-plans" / "legacy_architect.yaml")
        assert len(data["progression_path"]) == 3

    def test_each_plan_has_journal_prompts(self) -> None:
        sdir = CONFIG / "spiritual-plans"
        for f in sdir.glob("*.yaml"):
            if f.name in ("template.yaml", "_taxonomy.yaml"):
                continue
            data = load_yaml(f)
            assert "journal_prompts" in data, f"{f.name} missing journal_prompts"
            jp = data["journal_prompts"]
            assert "morning_static" in jp
            assert "evening_static" in jp


# ── 7f: Reference Docs ───────────────────────────────────


class TestReferenceDocs:
    def test_casey_session_transfer(self) -> None:
        path = DOCS / "adrian" / "reference" / "session-transfer-casey.md"
        assert path.exists()
        content = path.read_text(encoding="utf-8")
        assert "Session 1" in content or "Session" in content
        assert len(content) > 1000

    def test_persona_matrix_summary(self) -> None:
        path = DOCS / "adrian" / "reference" / "persona-matrix-summary.md"
        assert path.exists()
        content = path.read_text(encoding="utf-8")
        assert "Core Integrator" in content

    def test_scenario_db_structure(self) -> None:
        path = DOCS / "kiran" / "reference" / "scenario-db-structure.md"
        assert path.exists()
        content = path.read_text(encoding="utf-8")
        assert len(content) > 500

    def test_scenariomaster_spec(self) -> None:
        path = DOCS / "kiran" / "reference" / "scenariomaster-spec.md"
        assert path.exists()

    def test_wellness_plan_structure(self) -> None:
        path = DOCS / "sage" / "reference" / "wellness-plan-structure.md"
        assert path.exists()
        content = path.read_text(encoding="utf-8")
        assert "Wellness" in content

    def test_spiritual_plan_templates(self) -> None:
        path = DOCS / "victor" / "reference" / "spiritual-plan-templates.md"
        assert path.exists()
        content = path.read_text(encoding="utf-8")
        assert "Legacy Architect" in content or "Template" in content


# ── Cross-references ──────────────────────────────────────


class TestCrossReferences:
    """Verify data consistency across configs."""

    def test_ally_team_ids_valid(self) -> None:
        teams = load_yaml(CONFIG / "personas" / "ojas" / "teams.yaml")
        allies = load_yaml(CONFIG / "personas" / "ojas" / "allies.yaml")
        team_ids = {t["id"] for t in teams}
        for a in allies:
            assert a["team_id"] in team_ids, f"Ally {a['id']} has invalid team_id {a['team_id']}"

    def test_subteam_team_ids_valid(self) -> None:
        teams = load_yaml(CONFIG / "personas" / "ojas" / "teams.yaml")
        subteams = load_yaml(CONFIG / "personas" / "ojas" / "subteams.yaml")
        team_ids = {t["id"] for t in teams}
        for s in subteams:
            assert s["team_id"] in team_ids, f"Subteam {s['id']} has invalid team_id {s['team_id']}"

    def test_persona_tiers_reference_valid_ids(self) -> None:
        tiers = load_yaml(CONFIG / "personas" / "tiers.yaml")
        for tier_name, tc in tiers.items():
            for pid in tc.get("available_personas", []):
                assert 1 <= pid <= 12, f"Tier {tier_name} has invalid persona_id {pid}"
