#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""解析广东/浙江 2026 省自然科学基金清单 PDF → CSV

浙江：序号/项目名称/申请编号/申请人/依托单位/项目类别（无金额，按类别标准额折算）
广东：序号/主管部门/项目名称/申报单位/负责人/拟立项金额/拟拨付金额/项目类型
"""
import csv
import io
import os
import re

import fitz

BASE = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/销售分析/基金源文件'
ZJ = BASE + '/浙江_2026省自然科学基金拟资助项目清单.pdf'
GD = BASE + '/广东_2026省自然科学基金拟立项及资金安排表_转载件.pdf'

# ── 浙江 ───────────────────────────────────────────────
zrows = []
doc = fitz.open(ZJ)
for pno in range(doc.page_count):
    tabs = doc[pno].find_tables()
    for t in tabs.tables:
        for r in t.extract():
            cells = [(c or '').replace('\n', '').strip() for c in r]
            if len(cells) < 5:
                continue
            if not re.fullmatch(r'\d+', cells[0] or ''):
                continue
            # 序号, 项目名称, 申请编号, 申请人, 依托单位, 项目类别, 备注?
            no, name, code, pi, unit = cells[0], cells[1], cells[2], cells[3], cells[4]
            cat = cells[5] if len(cells) > 5 else ''
            if not re.match(r'[A-Z]{1,2}\d{2}', code):
                continue
            zrows.append({'prov': '浙江', 'no': no, 'name': name, 'code': code, 'pi': pi,
                          'unit': unit, 'cat': cat, 'amt': ''})
print('█ 浙江解析行数:', len(zrows))

# 浙江类别标准额（万元/项，按申请须知上限）
ZJ_RATE = {'重大项目': 100, '杰青项目': 80, '杰出青年': 80, '重点项目': 30, '探索项目': 10,
           '青年科学基金项目': 10, '青基项目': 10, '联合基金项目': 20, '青稞项目': 10}


def zj_amt(cat):
    for k, v in ZJ_RATE.items():
        if k in cat:
            return v
    return 10


for r in zrows:
    r['amt'] = zj_amt(r['cat'])
print('   类别分布:', {k: sum(1 for r in zrows if k in r['cat']) for k in ('重大', '杰青', '重点', '探索', '青年', '联合', '青稞')})
print('   折算总额: %.1f 万元' % sum(r['amt'] for r in zrows))

# ── 广东 ───────────────────────────────────────────────
grows = []
doc = fitz.open(GD)
for pno in range(doc.page_count):
    tabs = doc[pno].find_tables()
    for t in tabs.tables:
        for r in t.extract():
            cells = [(c or '').replace('\n', '').strip() for c in r]
            if len(cells) < 6:
                continue
            # 常见列序: 序号|主管部门|项目名称|申报单位|负责人|拟立项金额|拟拨付|类型
            no = cells[0]
            if not re.fullmatch(r'\d+', no or ''):
                continue
            # 金额列：找纯数字且 <=200 的单元格
            amt = ''
            for c in cells[5:]:
                if re.fullmatch(r'\d+(\.\d+)?', c or ''):
                    amt = c
                    break
            # 申报单位：包含大学/医院/学院/研究院/公司/中心 的单元格
            unit = ''
            for c in cells[2:6]:
                if re.search(r'(大学|学院|医院|研究院|研究所|中心|公司|实验室|疾控|科学院)', c):
                    unit = c
                    break
            # 负责人：2-4 个汉字、不是单位
            pi = ''
            for c in cells[3:7]:
                if re.fullmatch(r'[\u4e00-\u9fff]{2,4}', c or '') and c != unit:
                    pi = c
                    break
            name = cells[2] if len(cells) > 2 else ''
            cat = cells[-1] if re.search(r'(青年|面上|重点|杰青|探索)', cells[-1] or '') else ''
            if not unit:
                continue
            grows.append({'prov': '广东', 'no': no, 'name': name, 'code': '', 'pi': pi,
                          'unit': unit, 'cat': cat, 'amt': amt})
print('█ 广东解析行数:', len(grows))
if grows:
    print('   样例:', grows[0])
    print('   金额合计: %.1f 万元' % sum(float(r['amt']) for r in grows if r['amt']))

os.makedirs(BASE + '/parsed', exist_ok=True)
with io.open(BASE + '/parsed/浙江_2026省基金_明细.csv', 'w', encoding='utf-8-sig', newline='') as f:
    w = csv.DictWriter(f, fieldnames=['prov', 'no', 'name', 'code', 'pi', 'unit', 'cat', 'amt'])
    w.writeheader(); w.writerows(zrows)
with io.open(BASE + '/parsed/广东_2026省基金_明细.csv', 'w', encoding='utf-8-sig', newline='') as f:
    w = csv.DictWriter(f, fieldnames=['prov', 'no', 'name', 'code', 'pi', 'unit', 'cat', 'amt'])
    w.writeheader(); w.writerows(grows)
print('✅ CSV 已写入 parsed/')
