"""
Phase 1: 招标文件解析 — PDF 文本提取

用法:
    from phase1_parsing.extract_pdf_text import extract_text
    text = extract_text("data/招标文件.pdf")
"""

import os
import fitz


def extract_text(pdf_path: str, output_path: str = None) -> str:
    """从 PDF 提取文本内容。"""
    if not os.path.exists(pdf_path):
        raise FileNotFoundError(f"PDF 文件不存在: {pdf_path}")

    doc = fitz.open(pdf_path)
    pages_text = []
    for i, page in enumerate(doc):
        text = page.get_text()
        pages_text.append(f"=== PAGE {i+1} ===\n{text}")
    doc.close()

    full_text = "\n".join(pages_text)

    if output_path:
        os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(full_text)
        print(f"  [Phase1] 文本已保存: {output_path} ({len(full_text)} 字符)")

    return full_text


def extract_tender_sections(text: str) -> dict:
    """按招标文件章节分割文本。"""
    chapter_boundaries = [
        ("第一章", "投标邀请"),
        ("第二章", "投标人须知"),
        ("第三章", "政府采购政策功能"),
        ("第四章", "招标需求"),
        ("第五章", "评标方法与程序"),
        ("第六章", "投标文件有关格式"),
        ("第七章", "合同书格式和合同条款"),
        ("附件", "项目采购需求"),
    ]

    sections = {}
    for ch_name, ch_keyword in chapter_boundaries:
        idx = text.find(ch_name)
        if idx == -1:
            idx = text.find(ch_keyword)
        if idx != -1:
            next_idx = len(text)
            for nch_name, nch_kw in chapter_boundaries:
                if nch_name == ch_name:
                    continue
                ni = text.find(nch_name, idx + len(ch_name))
                if ni != -1 and ni < next_idx:
                    next_idx = ni
            sections[ch_name] = text[idx:next_idx].strip()

    return sections


def extract_project_overview(text: str) -> dict:
    """提取项目基本概况（名称、预算、期限等）"""
    overview = {}
    import re

    # 项目名称
    m = re.search(r"项目名称[：:]\s*(.+)", text)
    if m:
        overview["project_name"] = m.group(1).strip()

    # 预算金额
    m = re.search(r"预算金额[（(]元[）)]\s*[：:]\s*([\d,.]+)", text)
    if m:
        overview["budget"] = m.group(1).strip()

    # 采购需求关键词
    keywords = ["物业管理", "保洁", "保安", "绿化", "维修", "会务", "食堂"]
    found = [kw for kw in keywords if kw in text[:5000]]
    if found:
        overview["service_types"] = found

    # 服务期限
    m = re.search(r"服务期限[：:]\s*(.+)", text)
    if m:
        overview["service_period"] = m.group(1).strip()[:60]

    return overview


if __name__ == "__main__":
    import sys
    sys.stdout.reconfigure(encoding="utf-8")
    text = extract_text("data/松江区机关事务管理局物业管理服务招标文件.pdf")
    print(f"总页数: {text.count('=== PAGE')}, 总字符: {len(text)}")
    for name, content in extract_tender_sections(text).items():
        print(f"  {name}: {len(content)} 字符")
