"""
10_domain_sub_indices.py
领域子指数模块：财政 / 科技 / 治理 / 卫生 四大交叉领域子指数
Domain Sub-Indices Module: fiscal / tech / governance / health cross-cutting sub-indices

用途 / Purpose:
    V/C/F 是"资源重配置能力"的功能性三维度划分，但报告还需要按政策领域
    （而非功能维度）切分的子指数，供跨领域比较章节使用。本模块将指标
    重新映射到四个政策领域，并各自取标准化后指标的简单平均作为子指数。

依赖 / Dependencies: pandas
"""

import logging
from pathlib import Path

import pandas as pd

logging.basicConfig(level=logging.INFO, format="%(asctime)s  %(message)s")
log = logging.getLogger("10_domain_subindex")

DATA_DIR = Path("./data")

DOMAIN_MAP = {
    "fiscal": [
        "gov_expenditure_pct_gdp__minmax",
        "fiscal_balance_pct_gdp__minmax",
        "public_debt_pct_gdp__minmax",
        "tax_revenue_pct_gdp__minmax",
    ],
    "tech": [
        "patents_residents__minmax",
        "rd_expenditure_pct_gdp__minmax",
        "high_tech_exports_pct__minmax",
    ],
    "governance": [
        "regulatory_quality__minmax",
        "government_effectiveness__minmax",
        "rule_of_law__minmax",
        "corruption_control__minmax",
    ],
    "health": [
        "health_expenditure_pct_gdp__minmax",
        "social_protection_expenditure__minmax",
        "unemployment_benefit_coverage__minmax",
    ],
}


def domain_average(df: pd.DataFrame, cols: list) -> pd.Series:
    available = [c for c in cols if c in df.columns]
    if not available:
        return pd.Series(index=df.index, dtype=float)
    return df[available].mean(axis=1)


def main():
    panel = pd.read_csv(DATA_DIR / "panel_normalized_minmax.csv")
    result = panel[["iso3", "year"]].copy()

    for domain, cols in DOMAIN_MAP.items():
        result[f"{domain}_subindex"] = (domain_average(panel, cols) * 100).round(2)
        log.info("Computed %s sub-index (mean=%.2f)", domain, result[f"{domain}_subindex"].mean())

    result.to_csv(DATA_DIR / "domain_sub_indices.csv", index=False)
    log.info("Domain sub-indices saved -> data/domain_sub_indices.csv")


if __name__ == "__main__":
    main()
