#!/usr/bin/env python3
"""
自动招标检索爬虫 - 使用 Playwright
每天下午6点自动运行
提取完整招标信息：机构、参考号、项目描述、发布日期、截止日期、金额、状态
"""
from playwright.sync_api import sync_playwright
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
import re

# 关键词
KEYWORDS = ['solar', 'fotovoltaico', 'cargador', 'medidor', 'transformador', 
            'ctpt', 'recloser', 'led', 'medidor de agua', 'batería', 'battery']

# 获取今天日期
TODAY = datetime.now()
TODAY_STR = TODAY.strftime('%Y-%m-%d')
TODAY_SHORT = TODAY.strftime('%d/%m/%Y')

def extract_tenders(text, keyword):
    """从页面文本中提取今日招标的完整信息"""
    tenders = []
    lines = text.split('\n')
    
    for i, line in enumerate(lines):
        if TODAY_SHORT in line and 'UTC' in line:
            # 根据页面结构提取各字段
            # 行 i: 发布日期
            # 行 i-2: 项目描述
            # 行 i-4: 参考号
            # 行 i-6: 机构
            # 行 i+1: 截止日期
            # 行 i+3: 金额
            # 行 i+4: 状态
            
            ref = lines[i-4].strip() if i-4 >= 0 else ''
            desc = lines[i-2].strip() if i-2 >= 0 else ''
            auth = lines[i-6].strip() if i-6 >= 0 else ''
            deadline = lines[i+1].strip() if i+1 < len(lines) else ''
            price = lines[i+3].strip() if i+3 < len(lines) else ''
            status = lines[i+4].strip() if i+4 < len(lines) else ''
            
            if re.match(r'^[A-Z]+-\w+-\w+-\d{4}-\d{4,}$', ref):
                tenders.append({
                    'reference': ref,
                    'authority': auth[:60],
                    'description': desc[:200],
                    'publish_date': line.strip(),
                    'deadline': deadline,
                    'price': price,
                    'status': status,
                    'keyword': keyword
                })
    
    return tenders

def send_email(tenders):
    """发送邮件"""
    body = f"""📋 招标检索结果 ({TODAY_STR})

关键词：{', '.join(KEYWORDS)}

"""
    
    if tenders:
        body += f"找到 {len(tenders)} 条今日发布的相关招标：\n\n"
        for t in tenders:
            body += f"""【{t['reference']}】- 关键词: {t['keyword']}
机构：{t['authority']}
项目：{t['description']}
发布：{t['publish_date']}
截止：{t['deadline']}
金额：{t['price']}
状态：{t['status']}
---
"""
    else:
        body += "结论：今日无符合关键词的新招标\n"

    body += f"""
---
数据来源：https://comunidad.comprasdominicana.gob.do
自动生成 - {TODAY_STR}
"""

    msg = MIMEText(body, 'plain', 'utf-8')
    msg['Subject'] = f"招标检索结果 - {TODAY_STR}"
    msg['From'] = 'fengxia569@163.com'
    msg['To'] = 'feng.xia@hxgroup.com'

    server = smtplib.SMTP_SSL('smtp.163.com', 465)
    server.login('fengxia569@163.com', 'ZZ38a32nQEwTe2Wn')
    server.send_message(msg, 'fengxia569@163.com', ['feng.xia@hxgroup.com', 'evelyn@hxgroup.com'])
    server.quit()

def main():
    print(f"=== 开始自动招标检索 ({TODAY_STR}) ===")
    
    all_tenders = []
    
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_page()
        
        page.goto('https://comunidad.comprasdominicana.gob.do/Public/Tendering/ContractNoticeManagement/Index')
        page.wait_for_load_state('networkidle')
        page.wait_for_timeout(3000)
        
        # 对每个关键词进行搜索
        for kw in KEYWORDS:
            print(f"搜索: {kw}")
            
            page.fill('#txtAllWords2Search', '')
            page.wait_for_timeout(500)
            page.fill('#txtAllWords2Search', kw)
            page.click('#btnGoButton')
            page.wait_for_load_state('networkidle')
            page.wait_for_timeout(3000)
            
            text = page.inner_text('body')
            tenders = extract_tenders(text, kw)
            
            print(f"  今日相关: {len(tenders)} 条")
            all_tenders.extend(tenders)
        
        browser.close()
    
    # 去重
    seen = set()
    unique = []
    for t in all_tenders:
        if t['reference'] not in seen:
            seen.add(t['reference'])
            unique.append(t)
    
    print(f"\n今日相关招标总数: {len(unique)}")
    
    for t in unique[:5]:
        print(f"  - {t['reference']}: {t['description'][:50]}...")
    
    # 发送邮件
    send_email(unique)
    print("\n=== 完成 ===")

if __name__ == '__main__':
    main()
