"""Trial script to generate sample CAD drawing and test A3 PDF export & takeoff."""

from __future__ import annotations

import asyncio
from pathlib import Path

import ezdxf
import pymupdf

from app.modules.takeoff.application.drawing_takeoff_service import get_drawing_takeoff_service

vault = Path("storage/secure_vault")
vault.mkdir(parents=True, exist_ok=True)

# 1. Create realistic AutoCAD Engineering Drawing (Cống Hộp Bến Kem - Kè Đa Độ)
dxf_file = vault / "BAN_VE_MAU_CONG_BEN_KEM.dxf"
doc = ezdxf.new("R2018")
msp = doc.modelspace()

# Foundation boundary polylines (L = 25m, B = 6.5m, H = 4.5m)
msp.add_lwpolyline(
    [(0, 0), (25000, 0), (25000, 6500), (0, 6500)], close=True, dxfattribs={"color": 1}
)
# Culvert walls (left, center, right)
msp.add_line((0, 500), (25000, 500), dxfattribs={"color": 3})
msp.add_line((0, 3250), (25000, 3250), dxfattribs={"color": 3})
msp.add_line((0, 6000), (25000, 6000), dxfattribs={"color": 3})

# Upstream & Downstream Aprons
msp.add_lwpolyline(
    [(-4000, -1000), (0, 0), (0, 6500), (-4000, 7500)],
    close=True,
    dxfattribs={"color": 4},
)
msp.add_lwpolyline(
    [(25000, 0), (29000, -1000), (29000, 7500), (25000, 6500)],
    close=True,
    dxfattribs={"color": 4},
)

# Dimension annotations
msp.add_text("L = 25.000 mm", dxfattribs={"height": 350, "color": 2}).set_placement(
    (11000, -800)
)
msp.add_text(
    "B = 6.500 mm (2 Cua 2.5x2.5m)", dxfattribs={"height": 350, "color": 2}
).set_placement((-3500, 3250))
msp.add_text(
    "Cao do day cong: -1.85m", dxfattribs={"height": 350, "color": 2}
).set_placement((11000, 1500))

# Title block in TCVN3 (.VnTime)
msp.add_text(
    "C\xabng ty TNHH X\xa9y dung \xa7\xdanh S\xacn - MST: 0202111150",
    dxfattribs={"height": 450, "color": 7},
).set_placement((500, 9500))
msp.add_text(
    "D\xf9 \xa1n: K\xcc \xa7a \xa7\xe9 - H\xef th\xe8ng ceng qua de B\xd4n Kem (K2+150)",
    dxfattribs={"height": 500, "color": 7},
).set_placement((500, 8500))
msp.add_text(
    "H\xa1ng m\xf9c: Ceng h\xe5p 2 cua B=2x2.5m, L=25.0m - B\xaa t\xabng M300 \xae\xb5 1x2",
    dxfattribs={"height": 420, "color": 7},
).set_placement((500, 7500))

# Steel rebar table with AutoCAD MText escape sequences
mtext_content = (
    r"{\fArial;Bang Thong Ke Cot Thep Chinh (CB300-V):\P"
    r"1. Thep chiu luc ban day: %%c18a150, L=7.2m\P"
    r"2. Thep chiu luc vach cong: %%c18a200, L=5.0m\P"
    r"3. Thep ban nap cong: %%c20a150, L=7.2m\P"
    r"4. Thep dai phan bo: %%c10a200\P"
    r"Dung sai lap dat: %%p5mm | Do doc thoat nuoc: 0.5%%d}"
)
msp.add_mtext(mtext_content, dxfattribs={"char_height": 300, "color": 6}).set_location(
    (14000, 9500)
)

doc.saveas(str(dxf_file))
print("1. File CAD DXF mau da duoc tao thanh cong tai:")
print(f"   -> {dxf_file}")

# 2. Export to High-Resolution A3 PDF
service = get_drawing_takeoff_service()
pdf_a3_file = vault / "BAN_VE_MAU_CONG_BEN_KEM_Size_A3_300DPI.pdf"

pdf_bytes = service.export_drawing_to_a3_pdf(
    file_path=dxf_file,
    output_pdf_path=pdf_a3_file,
    orientation="landscape",
    color_scheme="print_ready",
    dpi=300,
)
print("\n2. Da xuat thanh cong file PDF Kho A3 Do Phan Giai Cao (300 DPI)!")
print(f"   -> File: {pdf_a3_file}")
print(f"   -> Dung luong: {len(pdf_bytes):,} bytes")

# 3. Verify A3 specifications with PyMuPDF
doc_pdf = pymupdf.open(str(pdf_a3_file))
page = doc_pdf[0]
width_mm = page.rect.width * 25.4 / 72.0
height_mm = page.rect.height * 25.4 / 72.0
print("\n3. Thong so ky thuat trang in PDF A3 thuc te:")
print(f"   - Chieu rong (Width) : {width_mm:.2f} mm (Chuan A3: 420.00 mm)")
print(f"   - Chieu cao (Height) : {height_mm:.2f} mm (Chuan A3: 297.00 mm)")
print(f"   - So trang           : {len(doc_pdf)} trang")
doc_pdf.close()


# 4. Run AI Takeoff Pipeline
async def run_takeoff():
    res = await service.process_drawing_file(
        file_path=dxf_file,
        filename="BAN_VE_MAU_CONG_BEN_KEM.dxf",
        drawing_hint="Cống hộp Bến Kem Kè Đa Độ Hải Phòng font TCVN3",
    )
    cost = float(res["metrics"]["total_estimated_cost_vnd"])
    c_m3 = float(res["metrics"]["total_concrete_volume_m3"])
    r_tons = float(res["metrics"]["total_rebar_weight_tons"])
    e_m3 = float(res["metrics"]["total_earthwork_volume_m3"])
    f_m2 = float(res["metrics"]["total_formwork_area_m2"])

    print("\n4. Ket qua BoQ & Boc tach Dinh muc Xay dung 2026 tu ban ve CAD:")
    print(f"   - Ma Ban Ve          : {res['takeoff']['drawing_code']}")
    print(f"   - Tieu De            : {res['takeoff']['drawing_title']}")
    print(f"   - Tong Du Toan BoQ   : {cost:,.0f} VND")
    print(f"   - Be Tong Ket Cau    : {c_m3:.2f} m3")
    print(f"   - Cot Thep CB300-V   : {r_tons:.3f} Tan")
    print(f"   - Dao Dap Dat K95    : {e_m3:.2f} m3")
    print(f"   - Van Khuon Dinh Hinh: {f_m2:.2f} m2")
    print(f"   - So luong dau viec  : {len(res['items'])} hang muc chi tiet\n")
    for idx, item in enumerate(res["items"], 1):
        amt = float(item["total_amount_vnd"])
        qty = float(item["quantity"])
        print(
            f"     [{idx}] {item['wbs_code']} | {item['norm_code']} | {item['item_name']} | {qty:.2f} {item['unit']} | {amt:,.0f} VND"
        )


asyncio.run(run_takeoff())
