"""Kiểm thử dựng lại dự toán Cống hộp Ông Đèn – Bà Lanh từ hồ sơ THẨM ĐỊNH (Luật 1: 100% số liệu nguồn).

Nguồn: "02. DToan thanh dinh ba Lanh.xls" (chuyển sang xlsx bằng Excel COM, không sửa nội dung),
đặt tại reports/ong_den/thamdinh_ba_lanh.xlsx. Các con số kỳ vọng dưới đây đọc trực tiếp từ
sheet "THKP hạng mục" và "Dự thầu" của file đó, không phải số tự đặt.
"""
from decimal import Decimal
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "reports" / "ong_den" / "thamdinh_ba_lanh.xlsx"

pytestmark = pytest.mark.skipif(not SRC.exists(), reason="Thiếu file nguồn thẩm định (dữ liệu khách hàng, không commit)")


@pytest.fixture(scope="module")
def est():
    from tools.estimation.ong_den_rebuild_estimate import load_appraised_estimate

    return load_appraised_estimate(SRC)


def test_two_work_packages_with_appraised_totals(est):
    # 2 hạng mục trong THKP: cống hộp (6.317.164.000) và hạng mục thứ hai (192.220.000)
    assert [hm.rounded_total for hm in est.packages] == [Decimal("6317164000"), Decimal("192220000")]
    assert est.grand_total == Decimal("6509384000")


def test_item_lines_reconcile_with_thkp_direct_costs(est):
    # Tổng thành tiền từng dòng công tác phải khớp dòng A1/B1/C1 "Theo đơn giá trực tiếp" của THKP
    hm1 = est.packages[0]
    assert abs(hm1.sum_items("vl") - hm1.thkp["A1"]) < Decimal("1")
    assert abs(hm1.sum_items("nc") - hm1.thkp["B1"]) < Decimal("1")
    assert abs(hm1.sum_items("m") - hm1.thkp["C1"]) < Decimal("1")


def test_key_quantities_from_appraised_boq(est):
    q = est.key_quantities()
    assert q["be_tong_m250_m3"] == pytest.approx(439.636, abs=0.01)
    assert q["cot_thep_tan"] == pytest.approx(57.638, abs=0.01)


def test_contract_discount_factor(est):
    k = est.contract_factor(Decimal("6482295000"))
    assert k == pytest.approx(6482295000 / 6509384000, rel=1e-9)


HD = ROOT / "reports" / "ong_den" / "phu_luc_01_02_HD.xlsx"


@pytest.mark.skipif(not HD.exists(), reason="Thiếu Phụ lục 01 HĐ")
def test_alignment_with_contract_annex(est):
    from tools.estimation.ong_den_rebuild_estimate import align_with_contract, load_contract_annex

    hd = load_contract_annex(HD)
    # Tổng thành tiền các dòng Phụ lục 01 = "TỔNG CÔNG TRÌNH = A+B" 6.482.295.379 đ
    assert abs(sum(h["amount"] for h in hd) - Decimal("6482295379")) < Decimal("2")
    pairs = align_with_contract(est, hd)
    key = {"AF.11213", "AF.12113", "AF.22313", "AF.61120", "AF.61321", "AF.61721", "AC.22111", "AC.12121"}
    matched = {it.code for _, (it, h) in pairs if it and h and it.code in key and it.qty == h["qty"]}
    assert matched == key


def test_export_workbook(est, tmp_path):
    from tools.estimation.ong_den_rebuild_estimate import export_workbook

    out = export_workbook(est, tmp_path / "du_toan.xlsx", contract_value=Decimal("6482295000"))
    import openpyxl

    wb = openpyxl.load_workbook(out)
    assert {"Du toan TD", "THKP", "Doi chieu HD", "Rui ro H1-H6", "Nguon"} <= set(wb.sheetnames)
