import requests
from app import app
from extensions import db
from models import SystemDict
from config import Config

def fetch_and_init():
    with app.app_context():
        # 定义需要抓取的字典代码及对应的本地类型
        target_mappings = {
            "nano_model": "ai_model",
            "aspect_ratio": "aspect_ratio",
            "ai_prompt": "prompt_tpl",
            "ai_image_size": "ai_image_size"
        }

        print("🚀 开始从远程接口获取字典数据...")
        
        for remote_code, local_type in target_mappings.items():
            try:
                url = f"{Config.DICT_URL}?platform={Config.PLATFORM}&code={remote_code}"
                response = requests.get(url, verify=False, timeout=15)
                
                if response.status_code == 200:
                    data = response.json().get("data", [])
                    print(f"📦 抓取到 {remote_code} ({len(data)} 条数据)")
                    
                    for item in data:
                        label = item.get("label")
                        value = item.get("value")
                        
                        # 检查本地是否已存在
                        exists = SystemDict.query.filter_by(dict_type=local_type, value=value).first()
                        if not exists:
                            new_dict = SystemDict(
                                dict_type=local_type,
                                label=label,
                                value=value,
                                cost=1 if local_type == 'ai_model' else 0, # 模型默认 1 积分，其余 0
                                is_active=True
                            )
                            db.session.add(new_dict)
                else:
                    print(f"❌ 抓取 {remote_code} 失败: HTTP {response.status_code}")
                    
            except Exception as e:
                print(f"⚠️ 抓取 {remote_code} 发生异常: {e}")

        db.session.commit()
        print("\n✅ 字典数据本地化初始化成功！")
        print("💡 您现在可以直接在数据库 system_dicts 表中修改模型的 cost (积分消耗) 字段。")

if __name__ == "__main__":
    fetch_and_init()
