#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：test_unique_fields.py
模块描述：测试唯一性字段配置功能

作者：czj
创建日期：2026-08-19
"""

import pytest
from app.executors.template_resolver import (
    TemplateResolver,
    _get_field_by_path,
    _set_field_by_path,
    _generate_unique_value,
)


class TestGetFieldByPath:
    """测试 _get_field_by_path 路径解析"""

    def test_simple_field(self):
        body = {"templateName": "测试模板", "duration": 15}
        assert _get_field_by_path(body, "templateName") == "测试模板"

    def test_simple_field_nonexistent(self):
        body = {"templateName": "测试模板"}
        assert _get_field_by_path(body, "nonexistent") is None

    def test_array_element(self):
        body = [{"templateName": "模板A"}, {"templateName": "模板B"}]
        assert _get_field_by_path(body, "$[0].templateName") == "模板A"
        assert _get_field_by_path(body, "$[1].templateName") == "模板B"

    @pytest.mark.parametrize("path,expected", [
        ("topicList[0].topicName", "话题A"),
        ("$[0].topicList[0].topicName", "话题A"),
        ("participantList", []),
        ("nonexistent", None),
    ])
    def test_various_paths(self, path, expected):
        body = [{"topicList": [{"topicName": "话题A"}], "participantList": []}]
        assert _get_field_by_path(body, path) == expected

    def test_deep_nested(self):
        body = {"level1": {"level2": {"level3": "deep_value"}}}
        assert _get_field_by_path(body, "level1.level2.level3") == "deep_value"

    def test_null_body(self):
        assert _get_field_by_path(None, "field") is None

    def test_empty_path(self):
        body = {"templateName": "测试模板"}
        assert _get_field_by_path(body, "") == body


class TestSetFieldByPath:
    """测试 _set_field_by_path 设置值"""

    def test_simple_field(self):
        body = {"templateName": "旧值"}
        _set_field_by_path(body, "templateName", "新值")
        assert body["templateName"] == "新值"

    def test_array_element(self):
        body = [{"templateName": "旧值A"}]
        _set_field_by_path(body, "$[0].templateName", "新值A")
        assert body[0]["templateName"] == "新值A"

    def test_nested_field(self):
        body = {"level1": {"level2": {"level3": "旧值"}}}
        _set_field_by_path(body, "level1.level2.level3", "新值")
        assert body["level1"]["level2"]["level3"] == "新值"

    def test_empty_path(self):
        body = {"templateName": "旧值"}
        _set_field_by_path(body, "", "新值")
        assert body["templateName"] == "旧值"  # 不应修改


class TestGenerateUniqueValue:
    """测试 _generate_unique_value 唯一值生成"""

    def test_suffix_strategy(self):
        assert _generate_unique_value("测试模板", "suffix", None, 0) == "测试模板_req_000"
        assert _generate_unique_value("测试模板", "suffix", None, 5) == "测试模板_req_005"
        assert _generate_unique_value("测试模板", "suffix", None, 999) == "测试模板_req_999"

    def test_suffix_strategy_empty_string(self):
        assert _generate_unique_value("", "suffix", None, 0) == "_req_000"

    def test_template_strategy(self):
        result = _generate_unique_value("原值", "template", "{__UUID__}", 0)
        assert result == "{__UUID__}"  # 占位符由后续 resolve() 处理

    def test_template_strategy_no_template(self):
        # strategy=template 但 template 为空 → 回退返回原值
        result = _generate_unique_value("原值", "template", None, 0)
        assert result == "原值"

    def test_unknown_strategy(self):
        result = _generate_unique_value("原值", "unknown", None, 0)
        assert result == "原值"


class TestApplyUniqueFields:
    """测试 TemplateResolver.apply_unique_fields 整体流程"""

    def test_no_unique_fields(self):
        body = {"templateName": "测试模板"}
        result = TemplateResolver.apply_unique_fields(body, [], 0)
        assert result == body

    def test_none_unique_fields(self):
        body = {"templateName": "测试模板"}
        result = TemplateResolver.apply_unique_fields(body, None, 0)
        assert result == body
        # 确保返回的是同一个对象（未深拷贝）
        assert result is body

    def test_single_field(self):
        body = {"templateName": "测试模板", "duration": 15}
        unique_fields = [{"field": "templateName", "strategy": "suffix"}]
        result = TemplateResolver.apply_unique_fields(body, unique_fields, 5)
        assert result["templateName"] == "测试模板_req_005"
        assert result["duration"] == 15  # 其他字段不变

    def test_array_body_field(self):
        body = [{"templateName": "测试模板", "duration": 15}]
        unique_fields = [{"field": "$[0].templateName", "strategy": "suffix"}]
        result = TemplateResolver.apply_unique_fields(body, unique_fields, 3)
        assert result[0]["templateName"] == "测试模板_req_003"

    def test_multiple_fields(self):
        body = {"templateName": "模板A", "messageName": "会议A"}
        unique_fields = [
            {"field": "templateName", "strategy": "suffix"},
            {"field": "messageName", "strategy": "suffix"},
        ]
        result = TemplateResolver.apply_unique_fields(body, unique_fields, 1)
        assert result["templateName"] == "模板A_req_001"
        assert result["messageName"] == "会议A_req_001"

    def test_deep_nested_field(self):
        body = [{"topicList": [{"topicName": "话题A"}]}]
        unique_fields = [{"field": "$[0].topicList[0].topicName", "strategy": "suffix"}]
        result = TemplateResolver.apply_unique_fields(body, unique_fields, 7)
        assert result[0]["topicList"][0]["topicName"] == "话题A_req_007"

    def test_does_not_mutate_original(self):
        """验证深拷贝：原始 body 不应被修改"""
        body = {"templateName": "原值"}
        unique_fields = [{"field": "templateName", "strategy": "suffix"}]
        TemplateResolver.apply_unique_fields(body, unique_fields, 0)
        assert body["templateName"] == "原值"  # 原对象不变

    def test_field_not_found_skips_silently(self):
        """字段在 body 中不存在 → 静默跳过"""
        body = {"templateName": "测试模板"}
        unique_fields = [{"field": "nonexistent", "strategy": "suffix"}]
        result = TemplateResolver.apply_unique_fields(body, unique_fields, 0)
        assert result == body

    def test_non_string_field_skips(self):
        """非字符串字段 → 跳过"""
        body = {"count": 123, "price": 45.6}
        unique_fields = [
            {"field": "count", "strategy": "suffix"},
            {"field": "price", "strategy": "suffix"},
        ]
        result = TemplateResolver.apply_unique_fields(body, unique_fields, 0)
        assert result["count"] == 123  # 不变
        assert result["price"] == 45.6  # 不变

    def test_body_is_none(self):
        """body 为 None → 返回 None"""
        result = TemplateResolver.apply_unique_fields(None, [{"field": "x", "strategy": "suffix"}], 0)
        assert result is None

    def test_body_is_string(self):
        """body 为字符串时 → 不处理（唯一化只对 JSON 结构有效）"""
        result = TemplateResolver.apply_unique_fields("hello", [{"field": "x", "strategy": "suffix"}], 0)
        assert result == "hello"