"""并表 Join 规则注册表 — security_type → 数据集映射 + Join 配置（硬编码，PRD D3）"""
from dataclasses import dataclass
from enum import Enum

from ldnode.loader.files import STK_DATA, CB_DATA, ETF_DATA, STK_FINA_IND
from ldnode.loader.schemas.models import File


class TimeAlignStrategy(Enum):
    EXACT = "exact"
    POINT_IN_TIME = "pit"
    AGGREGATE = "aggregate"


@dataclass(frozen=True)
class JoinRule:
    """(策略 Scope, 目标 Scope) 的 Join 规则。column_suffix 必须与 qnt_cross_asset_references 表一致。"""
    main_join_key: str
    aux_join_key: str
    time_key: str
    column_suffix: str
    time_align: TimeAlignStrategy = TimeAlignStrategy.EXACT
    aux_time_key: str | None = None

    def factor_key_to_source(self, factor_key: str) -> str:
        if self.column_suffix and factor_key.endswith(self.column_suffix):
            return factor_key[: -len(self.column_suffix)]
        return factor_key


# security_type → 数据集文件（PRD §3.5）
SCOPE_TO_FILE: dict[int, File] = {
    2: STK_DATA,
    1: CB_DATA,
    3: ETF_DATA,
    10: STK_FINA_IND,
    11: STK_FINA_IND,
}

# (策略 Scope, 目标 Scope) → JoinRule
JOIN_RULES: dict[tuple[int, int], JoinRule] = {
    (1, 2): JoinRule(
        main_join_key="code_stk",
        aux_join_key="code",
        time_key="trade_date",
        column_suffix="_stk",
    ),
    (1, 10): JoinRule(
        main_join_key="code_stk",
        aux_join_key="code",
        time_key="trade_date",
        column_suffix="_fin",
        time_align=TimeAlignStrategy.POINT_IN_TIME,
        aux_time_key="trade_date",
    ),
    (2, 10): JoinRule(
        main_join_key="code",
        aux_join_key="code",
        time_key="trade_date",
        column_suffix="_fin",
        time_align=TimeAlignStrategy.POINT_IN_TIME,
        aux_time_key="trade_date",
    ),
    (2, 11): JoinRule(
        main_join_key="code",
        aux_join_key="code",
        time_key="trade_date",
        column_suffix="_fina",
        time_align=TimeAlignStrategy.POINT_IN_TIME,
        aux_time_key="trade_date",
    ),
}
