#!/usr/bin/python3.12
"""从Dify工作流获取品牌热点（catName=brand_hotspots）并写入 origin_data/{MMDD}data.json 的 brand_hotspots 列表"""

import json, os, sys
from datetime import datetime
import urllib.request

# ── 配置 ──────────────────────────────────────────────────────
DIFY_URL = "http://43.164.190.156/v1/workflows/run"
DIFY_TOKEN = "app-ODwFQHiS45BuPerRlw77PVv8"
TODAY = datetime.now()
MMDD = TODAY.strftime('%m%d')
ORIGIN_PATH = f'/data/news/json/origin_data/{MMDD}data.json'

# ── 工具 ──────────────────────────────────────────────────────
def load_origin():
    if os.path.exists(ORIGIN_PATH):
        with open(ORIGIN_PATH, 'r', encoding='utf-8') as f:
            return json.load(f)
    return []

def save_origin(data):
    os.makedirs(os.path.dirname(ORIGIN_PATH), exist_ok=True)
    with open(ORIGIN_PATH, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def call_dify():
    """调用Dify工作流（blocking模式），返回解析后的品牌热点列表"""
    payload = json.dumps({
        "inputs": {"method": "GET", "catName": "brand_hotspots", "input": ""},
        "response_mode": "blocking",
        "user": "root"
    }).encode('utf-8')

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

    try:
        resp = urllib.request.urlopen(req, timeout=300)
    except Exception as e:
        raise ConnectionError(f"Dify请求失败: {e}")

    raw = resp.read().decode('utf-8', errors='replace')

    # 解析顶层 JSON
    top = json.loads(raw)
    # data.outputs.output 是 JSON 字符串（可能是条目数组，也可能是 section 包装 [{name,opinion,list}])
    output_str = top.get('data', {}).get('outputs', {}).get('output', '[]')
    # 解析为 Python 列表
    parsed = json.loads(output_str)

    if not isinstance(parsed, list):
        raise ValueError(f"解析结果非列表: {type(parsed)}")

    # 展开 section 包装结构：若元素含 'list' 字段则取 list 合并，否则视为条目数组
    brand_list = []
    for item in parsed:
        if isinstance(item, dict) and isinstance(item.get('list'), list):
            brand_list.extend(item['list'])
        else:
            brand_list.append(item)

    print(f"  ✅ Dify 返回 {len(brand_list)} 条品牌热点")
    return brand_list

def filter_items(items):
    """保留有真实标题的条目（新接口 brand 字段大量为空属常态，不按 brand 过滤）"""
    filtered = []
    for i in items:
        if not isinstance(i, dict):
            continue
        title = i.get('title', '')
        if title:
            if 'yesorno' not in i:
                i['yesorno'] = ''
            filtered.append(i)
    return filtered

def replace_brand_list(origin_data, new_list):
    """找到 brand_hotspots 段，清空后替换为新数据；
       若不存在则新建"""
    for section in origin_data:
        if section.get('name') == 'brand_hotspots':
            old_count = len(section.get('list', []))
            section['list'] = new_list
            print(f"  🔄 已清空旧数据({old_count}条)，写入{len(new_list)}条")
            return origin_data
    # 不存在则新建
    origin_data.append({
        "name": "brand_hotspots",
        "opinion": "",
        "list": new_list
    })
    print(f"  🆕 新建 brand_hotspots 段，写入{len(new_list)}条")
    return origin_data

def main():
    print(f'📅 日期: {TODAY.strftime("%Y-%m-%d")}, MMDD={MMDD}')
    print(f'📄 目标: {ORIGIN_PATH}')
    print()

    # 1. 调用 Dify
    print('🔍 请求 Dify 工作流（品牌热点 catName=brand_hotspots）...')
    brand_list = call_dify()

    if not brand_list:
        print('❌ Dify 返回为空，不写入')
        sys.exit(1)

    # 2. 过滤无品牌条目
    brand_list = filter_items(brand_list)
    print(f'  🧹 过滤后保留 {len(brand_list)} 条')

    # 3. 加载 origin_data
    origin_data = load_origin()
    print(f'📂 已读取 origin_data，共 {len(origin_data)} 个段')

    # 4. 替换 brand_hotspots（清空 + 插入）
    origin_data = replace_brand_list(origin_data, brand_list)

    # 5. 写入
    save_origin(origin_data)

    # 6. 统计
    for section in origin_data:
        if section.get('name') == 'brand_hotspots':
            total = len(section['list'])
            print(f'\n📊 汇总: brand_hotspots 共 {total} 条')
            break

    print(f'\n✅ 完成，已写入 {ORIGIN_PATH}')

if __name__ == '__main__':
    main()
