#!/usr/bin/env python3
"""
使用 OpenClaw 浏览器自动化进行招标爬取
"""
import subprocess
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
import json

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

TODAY = datetime.now().strftime('%Y-%m-%d')

def run_browser_command(keyword):
    """运行浏览器命令搜索关键词"""
    cmd = f'''
    osascript -e '
    tell application "Google Chrome"
        activate
        tell active tab of window 1
            set URL to "https://comunidad.comprasdominicana.gob.do/Public/Tendering/ContractNoticeManagement/Index"
        end tell
        delay 3
        tell active tab of window 1
            execute javascript "document.querySelector('input[type=search]').value = '';"
        end tell
        delay 1
        tell active tab of window 1
            execute javascript "document.querySelector('input[type=search]').value = '{keyword}'; document.querySelector('input[type=search]').dispatchEvent(new Event('input'));"
        end tell
        delay 1
        tell active tab of window 1
            execute javascript "document.querySelector('button[type=submit]').click();"
        end tell
        delay 3
    end tell
    '
    '''
    subprocess.run(cmd, shell=True, capture_output=True)
    return []

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

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

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

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

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

    server = smtplib.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}) ===")
    
    all_tenders = []
    
    for keyword in KEYWORDS:
        print(f"搜索: {keyword}")
        tenders = run_browser_command(keyword)
        all_tenders.extend(tenders)
    
    # 去重
    seen = set()
    unique = []
    for t in all_tenders:
        if t['reference'] not in seen:
            seen.add(t['reference'])
            unique.append(t)
    
    send_email(unique)
    print(f"邮件已发送，共 {len(unique)} 条")

if __name__ == '__main__':
    main()
