#!/usr/bin/python3.12
"""校验JSON文件中brand/vehicle/social的thumb图片是否为横向，非横向则用豆包生成"""
import json, sys, os, re, urllib.request
from datetime import datetime

API_KEY = "ark-563a4210-d804-47fa-a37a-40962192119b-ce6db"
MODEL = "doubao-seedream-4-0-250828"
API_URL = "https://ark.cn-beijing.volces.com/api/v3/images/generations"

# 横向比例判断（宽高比 >= 1.2 视为横向）
MIN_ASPECT = 1.2
MAX_ASPECT = 3.0


def get_image_size(path):
    """获取图片宽高"""
    try:
        from PIL import Image
        img = Image.open(path)
        return img.size
    except:
        pass
    return None


def is_landscape(w, h):
    return w and h and h > 0 and w / h >= MIN_ASPECT


def generate_image(title, source_url, thumb_path, summary=''):
    """直接用豆包API生成图片，不依赖外部脚本"""
    extra = f"，{summary[:80]}" if summary else ''
    # 豆包配图规则（2026-09-02 用户新增）：提示词不体现人物，只关注事件与品牌
    # ⚠️ 2026-09-24 修复：人名须物理删除（见 person_name_filter.py）——仅加否定后缀挡不住肖像
    from person_name_filter import sanitize as _sanitize, NO_PERSON_SUFFIX as _NOPS
    title = _sanitize(title) or '该品牌与产品的营销活动现场'
    prompt = f"{title}，配图要求：{_sanitize(extra)} 根据标题信息生成一张真实的产品/场景配图，车辆类型和外形必须与标题描述一致，横向构图，高清，16:9" + _NOPS

    payload = json.dumps({
        "model": MODEL,
        "prompt": prompt,
        "size": "1280x720",
        "n": 1,
        "response_format": "url"
    }).encode('utf-8')

    try:
        req = urllib.request.Request(
            API_URL, data=payload,
            headers={
                'Authorization': f'Bearer {API_KEY}',
                'Content-Type': 'application/json'
            },
            method='POST'
        )
        resp = urllib.request.urlopen(req, timeout=120)
        result = json.loads(resp.read().decode('utf-8'))

        img_url = result.get('data', [{}])[0].get('url', '')
        if not img_url:
            print(f'API未返回图片URL')
            return False

        # 下载图片
        img_req = urllib.request.Request(img_url, headers={'User-Agent': 'Mozilla/5.0'})
        img_resp = urllib.request.urlopen(img_req, timeout=60)
        os.makedirs(os.path.dirname(thumb_path), exist_ok=True)
        with open(thumb_path, 'wb') as f:
            f.write(img_resp.read())
        return True

    except Exception as e:
        print(f'API调用失败: {str(e)[:80]}')
        return False


def main():
    if len(sys.argv) < 2:
        print('用法: python3 check_thumbs.py <json文件路径>')
        sys.exit(1)

    json_path = sys.argv[1]
    img_base = os.path.dirname(json_path) + '/images'  # 假设图片目录在json同级的images下

    with open(json_path) as f:
        data = json.load(f)

    sections = ['brand_hotspots', 'vehicle_hotspots', 'social_hotspots']
    total_checked = 0
    total_fixed = 0

    for entry in data if isinstance(data, list) else []:
        sec = entry.get('name', '')
        if sec not in sections:
            continue

        print(f'\n--- {sec} ---')
        for i, item in enumerate(entry.get('list', [])):
            thumb = item.get('thumb', '')
            title = item.get('title', '')
            source_url = item.get('source_url', '')

            if not thumb:
                print(f'  [{i}] 无thumb: {title[:30]}')
                continue

            # 解析本地路径
            local_path = thumb
            if thumb.startswith('/images/'):
                local_path = f'/data/news{thumb}'
            elif not thumb.startswith('/'):
                local_path = f'/data/news/{thumb}'

            if not os.path.exists(local_path):
                # 有可能是外链
                if thumb.startswith('http'):
                    print(f'  [{i}] 外链: {title[:30]}')
                    # 尝试下载
                    try:
                        req = urllib.request.Request(thumb, headers={'User-Agent': 'Mozilla/5.0'})
                        resp = urllib.request.urlopen(req, timeout=15)
                        os.makedirs(os.path.dirname(local_path), exist_ok=True)
                        with open(local_path, 'wb') as f:
                            f.write(resp.read())
                    except:
                        print(f'    ⚠️ 下载失败')
                        continue
                else:
                    print(f'  [{i}] 文件不存在: {local_path}')
                    continue

            size = get_image_size(local_path)
            if not size:
                print(f'  [{i}] 无法读取: {title[:30]}')
                continue

            w, h = size
            aspect = w / h if h > 0 else 0
            orientation = '横向' if is_landscape(w, h) else '竖向'
            print(f'  [{i}] {w}x{h} ({aspect:.2f}) {orientation}: {title[:30]}', end='')

            if not is_landscape(w, h) or w / h > MAX_ASPECT:
                if w / h > MAX_ASPECT:
                    print(f' → 超宽banner({w/h:.1f}), 重新生成...', end=' ')
                else:
                    print(' → 需要重新生成...', end=' ')
                ok = generate_image(title, source_url, local_path, item.get('summary', ''))
                if ok:
                    new_size = get_image_size(local_path)
                    if new_size:
                        w2, h2 = new_size
                        print(f'✅ {w2}x{h2}')
                    else:
                        print('✅')
                    total_fixed += 1
                else:
                    print('❌')
            else:
                print()

            total_checked += 1

    print(f'\n{"="*40}')
    print(f'检查: {total_checked} 张')
    print(f'修复: {total_fixed} 张')
    
    # 图片尺寸压缩：宽度超过750px的缩放到750px
    resized = 0
    import subprocess
    # 从第一个有效的thumb路径获取图片目录
    scan_dir = ''
    for section in data:
        for item in section.get('list', []):
            t = (item.get('thumb') or '').strip()
            if t.startswith('/'):
                scan_dir = os.path.dirname(t)
                break
        if scan_dir:
            break
    if scan_dir and os.path.isdir(scan_dir):
        for fname in sorted(os.listdir(scan_dir)):
            if not fname.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')):
                continue
            fpath = os.path.join(scan_dir, fname)
            size = get_image_size(fpath)
            if size and size[0] > 750:
                new_h = int(size[1] * 750 / size[0])
                ext = fname.rsplit('.', 1)[1]
                tmp = fpath + '.tmp.' + ext
                subprocess.run(['ffmpeg', '-y', '-i', fpath, '-vf', 'scale=%d:%d' % (750, new_h), tmp],
                              capture_output=True, timeout=30)
                if os.path.exists(tmp):
                    os.replace(tmp, fpath)
                    resized += 1
    if resized:
        print(f'压缩: {resized} 张缩放到750px宽')
    
    print(f'{"="*40}')


if __name__ == '__main__':
    main()
