from __future__ import annotations

import asyncio
import json
from pathlib import Path

from app.api.dependencies import get_orchestrator

PROJECT_CODE = "DS-HK-2026-001"
PROJECT_NAME = "Cải tạo, sửa chữa tuyến đường từ nhà ông Nam đến cống chùa Hưng Khánh, thôn Tân Linh, xã Kiến Minh"
PACKAGE_CODE = "GOI-04-TCXL-MSTB"
PACKAGE_NAME = "Gói 04: Thi công xây lắp và mua sắm thiết bị"
CONTRACT_CODE = "08.3.SCKM/2026/HĐTCXD"
CONTRACT_NAME = "Hợp đồng thi công xây dựng công trình sửa chữa tuyến đường từ nhà ông Nam đến cống chùa Hưng Khánh"
INVESTOR_NAME = "Phòng Kinh tế xã Kiến Minh"
CONTRACTOR_NAME = "Công ty TNHH Xây dựng Định Sơn"
LOCATION = "Xã Kiến Minh, TP. Hải Phòng"
BASE_DIR = Path(
    "../DSCons/HĐ-2026/Phòng KT xã Kiến Minh-2026/Đường từ nhà ông Nam đến cống chùa Hưng Khánh"
)

FILES = [
    {
        "path": BASE_DIR / "Pháp lý/06. QD PHE KHLCNT.signed.pdf",
        "task_type": "procurement_tender",
        "document_type": "quyet_dinh_phe_duyet_khlcnt",
        "knowledge_type": "decision_document",
        "doc_stage": "pre_award",
        "doc_family": "decision",
        "required_for": ["pre_award", "contracting"],
        "issuer": "Phòng Kinh tế xã Kiến Minh",
        "signer": "Chưa bóc tách từ bản scan",
        "decision_no": "113/QĐ-KT",
        "issue_date": "2026-03-05",
        "effective_date": "2026-03-05",
        "title": "Quyết định phê duyệt KHLCNT",
        "tags": ["khlcnt", "phe_duyet", "phap_ly_nen", "lua_chon_nha_thau"],
        "related_docs": [
            "06.Bieu kem theo.doc",
            "03. QĐ PDKQLCNT TCXL & MSTB 06-03-2026.docx",
        ],
        "compliance_refs": [
            "Căn cứ pháp lý trước lựa chọn nhà thầu",
            "Chuỗi nhiệm vụ -> BCKTKT -> KHLCNT -> KQLCNT -> HĐ",
        ],
        "readiness_weight": 0.95,
    },
    {
        "path": BASE_DIR
        / "Gói 04 TCXL & MSTB/03. QĐ PDKQLCNT TCXL & MSTB 06-03-2026.docx",
        "task_type": "procurement_tender",
        "document_type": "quyet_dinh_phe_duyet_kqlcnt",
        "knowledge_type": "decision_document",
        "doc_stage": "contracting",
        "doc_family": "decision",
        "required_for": ["contracting"],
        "issuer": "Phòng Kinh tế xã Kiến Minh",
        "signer": "Chưa chuẩn hóa",
        "decision_no": "118/QĐ-KT",
        "issue_date": "2026-03-06",
        "effective_date": "2026-03-06",
        "title": "Quyết định phê duyệt KQLCNT gói 04",
        "tags": ["kqlcnt", "trung_thau", "goi_04", "can_cu_ky_hop_dong"],
        "related_docs": [
            "02. Biên bản thương thảo HĐTC.docx",
            "04. HD TCXD Sửa chữa tuyến đường từ nhà ông Nam đến cống chùa Hưng Khánh.docx",
        ],
        "compliance_refs": [
            "Căn cứ lựa chọn nhà thầu",
            "Tiền đề để ký hợp đồng thi công",
        ],
        "readiness_weight": 0.96,
    },
    {
        "path": BASE_DIR / "Gói 04 TCXL & MSTB/02. Biên bản thương thảo HĐTC.docx",
        "task_type": "contract_management",
        "document_type": "bien_ban_thuong_thao_hop_dong",
        "knowledge_type": "bid_negotiation_record",
        "doc_stage": "contracting",
        "doc_family": "contract",
        "required_for": ["contracting"],
        "issuer": "Phòng Kinh tế xã Kiến Minh và nhà thầu",
        "signer": "Đại diện các bên tham gia thương thảo",
        "decision_no": "",
        "issue_date": "2026-03-06",
        "effective_date": "2026-03-06",
        "title": "Biên bản thương thảo hợp đồng thi công",
        "tags": [
            "thuong_thao",
            "dieu_khoan_hop_dong",
            "gia_tri_hop_dong",
            "thanh_toan",
        ],
        "related_docs": [
            "03. QĐ PDKQLCNT TCXL & MSTB 06-03-2026.docx",
            "04. HD TCXD Sửa chữa tuyến đường từ nhà ông Nam đến cống chùa Hưng Khánh.docx",
        ],
        "compliance_refs": [
            "Cầu nối giữa KQLCNT và hợp đồng",
            "Nguồn đối chiếu điều khoản trước khi ký hợp đồng",
        ],
        "readiness_weight": 0.91,
    },
    {
        "path": BASE_DIR
        / "Gói 04 TCXL & MSTB/04. HD TCXD Sửa chữa tuyến đường từ nhà ông Nam đến cống chùa Hưng Khánh.docx",
        "task_type": "contract_management",
        "document_type": "hop_dong_thi_cong",
        "knowledge_type": "contract_document",
        "doc_stage": "contracting",
        "doc_family": "contract",
        "required_for": ["contracting", "payment", "finalization"],
        "issuer": "Phòng Kinh tế xã Kiến Minh",
        "signer": "Chủ đầu tư và Công ty TNHH Xây dựng Định Sơn",
        "decision_no": "",
        "issue_date": "2026-03-08",
        "effective_date": "2026-03-08",
        "title": "Hợp đồng thi công xây dựng",
        "tags": [
            "hop_dong_chinh",
            "dieu_khoan_thanh_toan",
            "quyet_toan",
            "bao_hanh",
            "thanh_ly",
        ],
        "related_docs": [
            "02. Biên bản thương thảo HĐTC.docx",
            "03. QĐ PDKQLCNT TCXL & MSTB 06-03-2026.docx",
        ],
        "compliance_refs": [
            "Căn cứ chính để kiểm tra điều kiện thanh toán",
            "Căn cứ chính để kiểm tra điều kiện quyết toán và thanh lý",
        ],
        "readiness_weight": 1.0,
    },
    {
        "path": BASE_DIR / "1.BD_DAI DONG.pdf",
        "task_type": "technical_delivery",
        "document_type": "ban_ve_thi_cong",
        "knowledge_type": "technical_drawing",
        "doc_stage": "execution",
        "doc_family": "drawing",
        "required_for": ["execution", "payment"],
        "issuer": "Đơn vị tư vấn thiết kế / hồ sơ kỹ thuật được duyệt",
        "signer": "Chưa bóc tách",
        "decision_no": "",
        "issue_date": "",
        "effective_date": "",
        "title": "Bản vẽ thi công - bình đồ",
        "tags": ["ban_ve", "binh_do", "thi_cong", "ky_thuat_hien_truong"],
        "related_docs": [
            "2.Chi tiet.pdf",
            "04. HD TCXD Sửa chữa tuyến đường từ nhà ông Nam đến cống chùa Hưng Khánh.docx",
        ],
        "compliance_refs": [
            "Căn cứ tổ chức thi công",
            "Căn cứ đối chiếu khối lượng và phạm vi kỹ thuật",
        ],
        "readiness_weight": 0.76,
    },
    {
        "path": BASE_DIR / "2.Chi tiet.pdf",
        "task_type": "technical_delivery",
        "document_type": "ban_ve_chi_tiet",
        "knowledge_type": "technical_drawing",
        "doc_stage": "execution",
        "doc_family": "drawing",
        "required_for": ["execution", "payment"],
        "issuer": "Đơn vị tư vấn thiết kế / hồ sơ kỹ thuật được duyệt",
        "signer": "Chưa bóc tách",
        "decision_no": "",
        "issue_date": "",
        "effective_date": "",
        "title": "Bản vẽ chi tiết",
        "tags": ["ban_ve", "chi_tiet", "cau_tao", "ky_thuat_hien_truong"],
        "related_docs": [
            "1.BD_DAI DONG.pdf",
            "04. HD TCXD Sửa chữa tuyến đường từ nhà ông Nam đến cống chùa Hưng Khánh.docx",
        ],
        "compliance_refs": [
            "Căn cứ triển khai chi tiết ngoài hiện trường",
            "Căn cứ kiểm soát chất lượng thi công theo thiết kế",
        ],
        "readiness_weight": 0.74,
    },
]


def chunk_text(text: str, chunk_size: int = 1400, overlap: int = 180) -> list[str]:
    cleaned = " ".join(text.split())
    if not cleaned:
        return []
    chunks: list[str] = []
    start = 0
    while start < len(cleaned):
        end = min(len(cleaned), start + chunk_size)
        chunks.append(cleaned[start:end])
        if end >= len(cleaned):
            break
        start = max(0, end - overlap)
    return chunks


def load_text(path: Path) -> str:
    suffix = path.suffix.lower()

    if suffix == ".docx":
        import zipfile

        fragments: list[str] = []
        with zipfile.ZipFile(path) as archive:
            xml_bytes = archive.read("word/document.xml")
        xml_text = xml_bytes.decode("utf-8", errors="ignore")
        for raw in xml_text.replace("</w:p>", "\n").split("<"):
            if raw.startswith("w:t") and ">" in raw:
                fragments.append(raw.split(">", 1)[1])
        text = " ".join(fragment.strip() for fragment in fragments if fragment.strip())
        if text.strip():
            return text

    if suffix in {".pdf", ".doc"}:
        try:
            from markitdown import MarkItDown

            md = MarkItDown()
            result = md.convert(str(path))
            text = getattr(result, "text_content", "") or ""
            if text.strip():
                return text
        except Exception:
            pass

    return path.read_text(encoding="utf-8", errors="ignore")


async def main() -> None:
    orchestrator = get_orchestrator()
    total = 0
    summary: list[dict[str, object]] = []

    for item in FILES:
        path = item["path"]
        if not path.exists():
            summary.append(
                {
                    "file": str(path),
                    "status": "missing",
                    "chunks": 0,
                }
            )
            continue

        text = load_text(path)
        chunks = chunk_text(text)
        payload = []
        for index, chunk in enumerate(chunks, start=1):
            metadata = {
                "project_code": PROJECT_CODE,
                "project_name": PROJECT_NAME,
                "package_code": PACKAGE_CODE,
                "package_name": PACKAGE_NAME,
                "contract_code": CONTRACT_CODE,
                "contract_name": CONTRACT_NAME,
                "investor_name": INVESTOR_NAME,
                "contractor_name": CONTRACTOR_NAME,
                "location": LOCATION,
                "task_type": item["task_type"],
                "doc_stage": item["doc_stage"],
                "doc_family": item["doc_family"],
                "knowledge_type": item["knowledge_type"],
                "document_type": item["document_type"],
                "required_for": item["required_for"],
                "issuer": item["issuer"],
                "signer": item["signer"],
                "decision_no": item["decision_no"],
                "issue_date": item["issue_date"],
                "effective_date": item["effective_date"],
                "source_file": str(path),
                "source_filename": path.name,
                "source_format": path.suffix.lower().lstrip("."),
                "section_title": item["title"],
                "chunk_index": index,
                "ingest_batch": "pilot_dot1",
                "tags": item["tags"],
                "related_docs": item["related_docs"],
                "compliance_refs": item["compliance_refs"],
                "readiness_weight": item["readiness_weight"],
                "required_for_payment": "payment" in item["required_for"],
                "required_for_finalization": "finalization" in item["required_for"],
                "required_for_commencement": "pre_award" in item["required_for"]
                or "contracting" in item["required_for"],
                "id": f"{PROJECT_CODE}::{item['document_type']}::{path.name}::chunk-{index}",
            }
            payload.append({"text": chunk, "metadata": metadata})

        if payload:
            inserted = await orchestrator.ingest_knowledge(
                task_type=str(item["task_type"]),
                chunks=payload,
            )
        else:
            inserted = 0

        total += inserted
        summary.append(
            {
                "file": str(path),
                "status": "ingested" if inserted else "empty",
                "chunks": inserted,
                "task_type": item["task_type"],
                "document_type": item["document_type"],
            }
        )

    print(
        json.dumps(
            {"status": "ok", "total_chunks": total, "files": summary},
            ensure_ascii=False,
            indent=2,
        )
    )


if __name__ == "__main__":
    asyncio.run(main())
