"""Tests for tsumugi.config module."""

import os
from pathlib import Path

import pytest

from tsumugi.config import (
    _project_id,
    build_config,
    find_instruction_files,
    find_memory_file,
    get_memory_path,
)


class TestProjectId:
    def test_windows_path(self):
        result = _project_id("C:\\Users\\space\\Desktop\\Tsumugi")
        assert result == "C-Users-space-Desktop-Tsumugi"

    def test_different_paths_produce_different_ids(self):
        r1 = _project_id("C:\\Users\\space\\ProjectA")
        r2 = _project_id("C:\\Users\\space\\ProjectB")
        assert r1 != r2
        assert "ProjectA" in r1
        assert "ProjectB" in r2

    def test_trailing_separator_stripped(self):
        r1 = _project_id("C:\\Users\\space\\Desktop\\Tsumugi\\")
        r2 = _project_id("C:\\Users\\space\\Desktop\\Tsumugi")
        assert r1 == r2


class TestFindInstructionFiles:
    def test_finds_tsumugi_md(self, tmp_path):
        md = tmp_path / "TSUMUGI.md"
        md.write_text("# test instructions", encoding="utf-8")
        results = find_instruction_files(tmp_path)
        assert len(results) >= 1
        found_paths = [str(p) for p, _ in results]
        assert str(md) in found_paths

    def test_empty_when_no_file(self, tmp_path):
        subdir = tmp_path / "deep" / "nested"
        subdir.mkdir(parents=True)
        results = find_instruction_files(subdir)
        # May find TSUMUGI.md in parent dirs, but not in this temp tree
        for path, _ in results:
            assert "deep" not in str(path) or path.exists()


class TestMemoryFile:
    def test_get_memory_path_unique_per_project(self):
        p1 = get_memory_path("/project/a")
        p2 = get_memory_path("/project/b")
        assert p1 != p2

    def test_find_memory_file_returns_none_when_missing(self, tmp_path):
        result = find_memory_file(tmp_path)
        assert result is None

    def test_find_memory_file_reads_content(self, tmp_path, monkeypatch):
        """Test that find_memory_file reads from the correct project path."""
        from tsumugi import config as config_module

        fake_projects = tmp_path / "projects"
        monkeypatch.setattr(config_module, "PROJECTS_DIR", fake_projects)

        pid = _project_id(tmp_path)
        mem_dir = fake_projects / pid / "memory"
        mem_dir.mkdir(parents=True)
        mem_file = mem_dir / "MEMORY.md"
        mem_file.write_text("# test memory", encoding="utf-8")

        result = find_memory_file(tmp_path)
        assert result is not None
        assert result[1] == "# test memory"


class TestBuildConfig:
    def test_default_provider(self):
        config = build_config()
        assert config.provider in ("anthropic", "openai")

    def test_cli_overrides(self):
        config = build_config(
            cli_provider="openai",
            cli_model="gpt-4o",
            cli_api_key="test-key",
            cli_max_tokens=4096,
        )
        assert config.provider == "openai"
        assert config.model == "gpt-4o"
        assert config.api_key == "test-key"
        assert config.max_tokens == 4096

    def test_env_overrides(self, monkeypatch):
        monkeypatch.setenv("TSUMUGI_PROVIDER", "openai")
        monkeypatch.setenv("OPENAI_API_KEY", "env-key")
        config = build_config()
        assert config.provider == "openai"
        assert config.api_key == "env-key"

    def test_has_working_dir(self):
        config = build_config()
        assert config.working_dir == os.getcwd()
