from __future__ import annotations

from uuid import uuid4

from sync_state_machine.domain.project.api_handler import _merge_project_all_info_fields
from sync_state_machine.domain.project.sync_node import ProjectSyncNode


def test_merge_project_all_info_fields_flattens_extension_investment_fields() -> None:
    project_data = {
        "id": "project-1",
        "name": "Demo Project",
        "dynamic_investment": 123.0,
    }
    all_info = {
        "project": {"id": "project-1"},
        "hydropower_extension": {
            "implementation_estimate": 1000.0,
            "static_total_investment": 990.0,
            "completed_investment": 120.0,
            "total_contract_quantity": 50.0,
        },
    }

    merged = _merge_project_all_info_fields(project_data, all_info)

    assert merged["dynamic_investment"] == 123.0
    assert merged["implementation_estimate"] == 1000.0
    assert merged["static_total_investment"] == 990.0
    assert merged["completed_investment"] == 120.0
    assert merged["total_contract_quantity"] == 50.0


def test_merge_project_all_info_fields_keeps_existing_project_values() -> None:
    project_data = {
        "id": "project-1",
        "implementation_estimate": 2000.0,
        "static_total_investment": 1800.0,
    }
    all_info = {
        "hydropower_extension": {
            "implementation_estimate": 1000.0,
            "static_total_investment": 990.0,
            "completed_investment": 120.0,
        },
    }

    merged = _merge_project_all_info_fields(project_data, all_info)

    assert merged["implementation_estimate"] == 2000.0
    assert merged["static_total_investment"] == 1800.0
    assert merged["completed_investment"] == 120.0


def test_project_sync_node_preserves_extension_backed_fields() -> None:
    project_id = str(uuid4())
    data = {
        "_id": project_id,
        "id": project_id,
        "project_type": "hydropower",
        "region_name": ["中国", "测试省"],
        "region_path": ["100000", "110000"],
        "province": "110000",
        "is_domestic": True,
        "company_id": str(uuid4()),
        "company_name": "测试公司",
        "address": "测试地址",
        "code": "P-001",
        "name": "测试项目",
        "progress_type": "A",
        "dynamic_investment": 100.0,
        "complete_investment": 80.0,
        "implementation_estimate": 120.0,
        "static_total_investment": 110.0,
        "completed_investment": 70.0,
    }

    node = ProjectSyncNode(node_id=str(uuid4()), data_id=data["id"], data=data)
    normalized = node.get_data()

    assert normalized is not None
    assert normalized["implementation_estimate"] == 120.0
    assert normalized["static_total_investment"] == 110.0
    assert normalized["completed_investment"] == 70.0
