"""Tests for assistant configuration helpers."""

import json
from pathlib import Path

from yier_agents.src.config import YIERConfig


def write_config(config_dir: Path, payload: dict) -> None:
    """Persist one config payload for tests."""
    config_dir.mkdir(parents=True, exist_ok=True)
    (config_dir / ".yier.json").write_text(json.dumps(payload), encoding="utf-8")


def test_read_assistant_settings_uses_current_defaults(tmp_path: Path):
    """Assistant settings should match the current hard-coded CLI defaults."""
    workspace_root = tmp_path / "workspace"
    workspace_root.mkdir()
    config_dir = tmp_path / "config"
    config_dir.mkdir()

    settings = YIERConfig.read_assistant_settings(
        cwd=workspace_root,
        config_dir=config_dir,
    )

    assert settings.workspace_root == workspace_root.resolve()
    assert settings.session_storage_path == (
        workspace_root / ".agent_storage" / "sessions"
    ).resolve()
    assert settings.prompt_history_path == (
        workspace_root / ".agent_storage" / "prompt_history.txt"
    ).resolve()
    assert settings.allowed_roots == (
        workspace_root.resolve(),
        (workspace_root / ".agent_storage" / "sessions").resolve(),
    )
    assert settings.include_skill_directories_in_allowed_roots is True
    assert settings.max_iterations == 100
    assert settings.run_command.allow_shell is False


def test_read_assistant_settings_resolves_paths_and_shell_override(tmp_path: Path):
    """Assistant config should override roots, paths, and shell behavior."""
    workspace_root = tmp_path / "workspace"
    workspace_root.mkdir()
    config_dir = tmp_path / "config"
    write_config(
        config_dir,
        {
            "assistant": {
                "workspaceRoot": "workspace",
                "sessionStoragePath": ".runtime/sessions",
                "promptHistoryPath": ".runtime/history.txt",
                "allowedRoots": [
                    ".",
                    "docs",
                ],
                "includeSkillDirectoriesInAllowedRoots": False,
                "maxIterations": 12,
                "systemPrompt": "Custom helper prompt",
                "runCommand": {
                    "allowShell": True,
                    "shellProgram": "/bin/zsh",
                },
                "compaction": {
                    "enabled": False,
                    "triggerMessageCount": 18,
                    "preserveRecentMessages": 4,
                    "summaryMaxTokens": 256,
                },
            }
        },
    )

    settings = YIERConfig.read_assistant_settings(
        cwd=tmp_path,
        config_dir=config_dir,
    )

    assert settings.workspace_root == workspace_root.resolve()
    assert settings.session_storage_path == (
        workspace_root / ".runtime" / "sessions"
    ).resolve()
    assert settings.prompt_history_path == (
        workspace_root / ".runtime" / "history.txt"
    ).resolve()
    assert settings.allowed_roots == (
        workspace_root.resolve(),
        (workspace_root / "docs").resolve(),
    )
    assert settings.include_skill_directories_in_allowed_roots is False
    assert settings.max_iterations == 12
    assert settings.system_prompt == "Custom helper prompt"
    assert settings.run_command.allow_shell is True
    assert settings.run_command.shell_program == "/bin/zsh"
    assert settings.compaction.enabled is False
    assert settings.compaction.trigger_message_count == 18
    assert settings.compaction.preserve_recent_messages == 4
    assert settings.compaction.summary_max_tokens == 256


def test_resolve_runtime_config_dir_prefers_local_project_file(tmp_path: Path):
    """A project-local .yier.json should be preferred for CLI config."""
    workspace_root = tmp_path / "workspace"
    workspace_root.mkdir()
    write_config(workspace_root, {"assistant": {}})

    resolved = YIERConfig.resolve_runtime_config_dir(workspace_root)

    assert resolved == workspace_root.resolve()
