# Generated by Django


from django.db import migrations, models


def migrate_old_invalidation_data(apps, schema_editor):
    """
    迁移旧的证伪数据到新格式

    旧格式 -> 新格式：
    - invalidation_rules -> invalidation_rule_json
    - invalidation_logic -> invalidation_description

    旧格式字段名：indicator, condition
    新格式字段名：indicator_code, operator
    """
    InvestmentSignalModel = apps.get_model('signal', 'InvestmentSignalModel')

    for signal in InvestmentSignalModel.objects.all():
        # 如果已有新格式，跳过
        if signal.invalidation_rule_json:
            continue

        # 尝试从旧格式迁移
        old_rules = signal.invalidation_rules
        if old_rules and isinstance(old_rules, dict):
            # 转换旧格式到新格式
            try:
                new_rules = convert_old_format_to_new(old_rules)
                signal.invalidation_rule_json = new_rules
            except (KeyError, ValueError):
                # 转换失败，保持为空
                pass

        # 迁移描述字段
        if not signal.invalidation_description and signal.invalidation_logic:
            signal.invalidation_description = signal.invalidation_logic
        elif not signal.invalidation_description:
            # 使用 get_human_readable_rules 生成描述
            signal.invalidation_description = signal.get_human_readable_rules()

        signal.save(update_fields=[
            'invalidation_rule_json',
            'invalidation_description'
        ])


def convert_old_format_to_new(old_rules):
    """
    转换旧格式到新格式

    旧格式:
    {
        "conditions": [
            {
                "indicator": "PMI",  # 旧字段名
                "condition": "lt",   # 旧字段名
                "threshold": 50.0,
                "duration": 2,
                "compare_with": "prev_value"
            }
        ],
        "logic": "AND"
    }

    新格式:
    {
        "conditions": [
            {
                "indicator_code": "CN_PMI_MANUFACTURING",  # 新字段名
                "indicator_type": "macro",
                "operator": "lt",  # 新字段名
                "threshold": 50.0,
                "duration": 2,
                "compare_with": "prev_value"
            }
        ],
        "logic": "AND"
    }
    """
    # 指标代码映射（旧名称 -> 新代码）
    indicator_code_map = {
        'PMI': 'CN_PMI_MANUFACTURING',
        'CPI': 'CN_CPI_YOY',
        'PPI': 'CN_PPI_YOY',
        'M2': 'CN_M2_YOY',
        'SHIBOR': 'SHIBOR_1M',
        'GDP': 'CN_GDP_YOY',
    }

    # 指标类型映射
    macro_indicators = {
        'CN_PMI_MANUFACTURING', 'CN_PMI_NON_MANUFACTURING',
        'CN_GDP_YOY', 'CN_CPI_YOY', 'CN_CPI_MOY',
        'CN_PPI_YOY', 'CN_PPI_MOY', 'CN_M2_YOY',
    }

    new_conditions = []
    for cond in old_rules.get('conditions', []):
        # 转换 indicator -> indicator_code
        old_indicator = cond.get('indicator', '')
        new_indicator_code = indicator_code_map.get(old_indicator, old_indicator)

        # 转换 condition -> operator（名称相同）
        operator = cond.get('condition', cond.get('operator', 'lt'))

        # 确定 indicator_type
        if new_indicator_code in macro_indicators:
            indicator_type = 'macro'
        else:
            indicator_type = 'market'

        new_condition = {
            'indicator_code': new_indicator_code,
            'indicator_type': indicator_type,
            'operator': operator,
            'threshold': cond.get('threshold'),
        }

        # 可选字段
        if cond.get('duration'):
            new_condition['duration'] = cond['duration']
        if cond.get('compare_with'):
            new_condition['compare_with'] = cond['compare_with']

        new_conditions.append(new_condition)

    return {
        'conditions': new_conditions,
        'logic': old_rules.get('logic', 'AND')
    }


class Migration(migrations.Migration):
    dependencies = [
        ('signal', '0004_investmentsignalmodel_avg_backtest_return_and_more'),
    ]

    operations = [
        # 添加新字段
        migrations.AddField(
            model_name='investmentsignalmodel',
            name='invalidation_rule_json',
            field=models.JSONField(
                blank=True,
                help_text='结构化证伪规则 (InvalidationRule.to_dict())',
                null=True
            ),
        ),
        migrations.AddField(
            model_name='investmentsignalmodel',
            name='invalidation_description',
            field=models.TextField(
                blank=True,
                help_text='证伪逻辑的人类可读描述'
            ),
        ),
        # 迁移数据
        migrations.RunPython(migrate_old_invalidation_data),
    ]
