#!/usr/bin/env python3
"""上传文件到Dify并执行翻译工作流"""
import json, os, sys, uuid, urllib.request, mimetypes, re, shutil
from datetime import datetime, timedelta
import io

WORKFLOW_URL = "http://43.164.190.156/v1/workflows/run"
FILE_UPLOAD_URL = "http://43.164.190.156/v1/files/upload"
TOKEN = "app-LmguBwusYJguBMxIxAaJEHyx"

def upload_file(filepath, user="root"):
    if not os.path.exists(filepath):
        raise FileNotFoundError(f"文件不存在: {filepath}")

    boundary = uuid.uuid4().hex
    body = io.BytesIO()
    # 改为.txt后缀绕过Dify文件类型校验
    upload_name = os.path.basename(filepath).rsplit('.', 1)[0] + '.txt'

    body.write(f'--{boundary}\r\n'.encode())
    body.write(f'Content-Disposition: form-data; name="file"; filename="{upload_name}"\r\n'.encode())
    body.write(f'Content-Type: text/plain\r\n\r\n'.encode())
    with open(filepath, 'rb') as f:
        body.write(f.read())
    body.write(b'\r\n')

    body.write(f'--{boundary}\r\n'.encode())
    body.write(f'Content-Disposition: form-data; name="user"\r\n\r\n'.encode())
    body.write(f'{user}\r\n'.encode())
    body.write(f'--{boundary}--\r\n'.encode())

    req = urllib.request.Request(FILE_UPLOAD_URL, data=body.getvalue(),
        headers={'Authorization': f'Bearer {TOKEN}', 'Content-Type': f'multipart/form-data; boundary={boundary}'},
        method='POST')

    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            resp = json.loads(r.read().decode('utf-8'))
            file_id = resp.get('id')
            if not file_id:
                raise Exception(f"上传返回无id: {resp}")
            print(f"  ✅ {os.path.basename(filepath)} → id={file_id}")
            return file_id
    except urllib.error.HTTPError as e:
        raise Exception(f"上传失败 HTTP {e.code}: {e.read().decode('utf-8')[:200]}")


def call_workflow(datafile_id, keepfile_id, user="root"):
    payload = json.dumps({
        "inputs": {
            "datafile": {"transfer_method": "local_file", "upload_file_id": datafile_id, "type": "document"},
            "keepfile": {"transfer_method": "local_file", "upload_file_id": keepfile_id, "type": "document"}
        },
        "response_mode": "blocking",
        "user": user
    }).encode()

    req = urllib.request.Request(WORKFLOW_URL, data=payload,
        headers={'Authorization': f'Bearer {TOKEN}', 'Content-Type': 'application/json'},
        method='POST')

    try:
        with urllib.request.urlopen(req, timeout=600) as r:
            return json.loads(r.read().decode('utf-8'))
    except urllib.error.HTTPError as e:
        raise Exception(f"工作流失败 HTTP {e.code}: {e.read().decode('utf-8')[:200]}")


def main():
    # 优先用明天，不存在则回退到今天
    tomorrow = (datetime.now() + timedelta(days=1))
    mmdd = tomorrow.strftime("%m%d")
    datafile = f"/data/news/json/{mmdd}data.json"
    if not os.path.exists(datafile):
        mmdd = datetime.now().strftime("%m%d")
        datafile = f"/data/news/json/{mmdd}data.json"
        print(f"  ⚠️ 明日文件不存在，回退到今天: {mmdd}")
    keepfile = "/data/news/translate_word.md"

    print(f"[{datetime.now().strftime('%H:%M:%S')}] Dify工作流（文件上传）")
    print(f"  datafile: {datafile}")
    print(f"  keepfile: {keepfile}")

    print("\n--- 上传文件 ---")
    did = upload_file(datafile)
    kid = upload_file(keepfile)

    print("\n--- 调用工作流 ---")
    resp = call_workflow(did, kid)

    # 提取outputs
    outputs = resp.get('data', {}).get('output', {}) or resp.get('data', {}).get('outputs', {}).get('output', {})
    status = resp.get('data', {}).get('status')
    elapsed = resp.get('data', {}).get('elapsed_time', 0)

    print(f"  status: {status}, elapsed: {elapsed:.1f}s")

    # 写入输出
    tmp_path = "/data/news/json/ko-dify-tmp.json"
    if outputs:
        with open(tmp_path, 'w', encoding='utf-8') as f:
            json.dump(outputs, f, ensure_ascii=False, indent=2)
        print(f"✅ outputs已写入 {tmp_path}")
        
        # 自动复制到 ko-{MMDD}data.json
        mmdd = re.search(r'/(\d{4})data\.json$', datafile)
        if mmdd:
            ko_path = f"/data/news/json/ko-{mmdd.group(1)}data.json"
            shutil.copy2(tmp_path, ko_path)
            print(f"✅ 已复制到 {ko_path}")
    else:
        print(f"⚠️ 无output，写入 {tmp_path}")
        json.dump({"error": "no_output", "raw": str(resp)[:500]}, open(tmp_path, 'w'))

    print("\n--- 输出结果 keys ---")
    if outputs:
        for k in outputs.keys():
            v = outputs[k]
            if isinstance(v, str) and len(v) > 200:
                print(f"  {k}: {v[:150]}...")
            elif isinstance(v, list):
                print(f"  {k}: [{len(v)}条] {str(v[0])[:100] if v else 'empty'}")
            else:
                print(f"  {k}: {json.dumps(v, ensure_ascii=False)[:200]}")


if __name__ == '__main__':
    main()
