#!/usr/bin/env python3
"""咨询表单提交处理 - 通过公司群 relay 发送通知"""
import cgi
import json
import urllib.request
import os
import sys

def send_to_group(message):
    """通过 company_group_relay 发送消息到群"""
    try:
        data = json.dumps({"msg": message, "source": "咨询表单"}).encode()
        req = urllib.request.Request(
            "http://127.0.0.1:8800/send",
            data=data,
            headers={"Content-Type": "application/json"}
        )
        resp = urllib.request.urlopen(req, timeout=5)
        return resp.status == 200
    except Exception as e:
        return False

def main():
    # 解析 POST 数据
    content_length = int(os.environ.get("CONTENT_LENGTH", 0))
    body = sys.stdin.read(content_length) if content_length > 0 else ""
    
    try:
        data = json.loads(body) if body else {}
    except:
        data = {}
    
    name = data.get("name", "未知")
    phone = data.get("phone", "未知")
    message = data.get("message", "")
    
    # 发送到公司群
    text = f"📩 网站新咨询\n姓名: {name}\n电话: {phone}\n需求: {message or '未填写'}"
    sent = send_to_group(text)
    
    # 输出 JSON 响应
    print("Content-Type: application/json")
    print()
    print(json.dumps({"ok": True, "sent": sent, "message": "咨询已提交"}))

if __name__ == "__main__":
    main()
