"""
测试 返回结果截断机制
"""
import sys
import os
import uuid
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

from aacode.config import settings


class TestTruncationConfig:
    """配置层面验证"""

    def test_skill_max_result_chars_exists(self):
        assert hasattr(settings.limits, "skill_max_result_chars")

    def test_skill_max_result_chars_default(self):
        assert settings.limits.skill_max_result_chars == 5000


class TestRunSkillsTruncation:
    """验证 _run_skills 中的截断逻辑"""

    def test_code_exists(self):
        from aacode.core.main_agent import MainAgent
        import inspect
        src = inspect.getsource(MainAgent._run_skills)
        assert "skill_max_result_chars" in src
        assert "skill_result_" in src
        assert "Grep the file" in src
        assert "Preview (2000 chars)" in src
        assert "getattr(settings.limits" in src


class TestPlaywrightExtractNote:
    """验证 Playwright extract step 的 note 引导"""

    def test_note_in_source(self):
        from aacode.skills.playwright.main import _step_extract
        import inspect
        src = inspect.getsource(_step_extract)
        assert "what" in src
        assert "all" in src


class TestShellOutputSaving:
    """验证 run_shell 截断时存文件"""

    def test_save_logic_in_source(self):
        from aacode.tools.atomic_tools import AtomicTools
        import inspect
        src = inspect.getsource(AtomicTools.run_shell)
        assert "Full output saved to" in src
        assert "Grep the file" in src
        assert "project_path" in src


class TestFetchUrlContentSaving:
    """验证 fetch_url 截断时存文件"""

    def test_save_logic_in_source(self):
        from aacode.tools.web_tools import WebTools
        import inspect
        src = inspect.getsource(WebTools.fetch_url)
        assert "tool_content_" in src
        assert "Grep the file" in src
        assert "project_path" in src

    def test_file_created_when_truncated(self):
        """模拟截断，验证文件生成"""
        import tempfile
        import shutil
        tmp = Path(tempfile.mkdtemp())
        try:
            extracts = tmp / ".aacode" / "extracts"
            extracts.mkdir(parents=True, exist_ok=True)
            file_path = extracts / f"tool_stdout_{uuid.uuid4().hex[:8]}.txt"
            full_text = "x" * 10000
            file_path.write_text(full_text, encoding="utf-8")
            assert file_path.exists()
            assert file_path.read_text(encoding="utf-8") == full_text
            assert file_path.stat().st_size == 10000
        finally:
            shutil.rmtree(tmp, ignore_errors=True)


class TestFetchUrlContentSaving:
    """验证 fetch_url 截断时存文件"""

    def test_save_logic_in_source(self):
        from aacode.tools.web_tools import WebTools
        import inspect
        src = inspect.getsource(WebTools.fetch_url)
        assert "tool_content_" in src
        assert "Grep the file" in src
