"""
股票对比分析

用法: python stock_compare.py <stock_codes> [--metrics <list>]
  stock_codes: 逗号分隔的股票代码，如 600519,000858(A股) 或 03888,00700(港股)
  --metrics:   对比指标，逗号分隔（默认全部）

AKShare接口:
  A股主: ak.stock_zh_a_spot() — 新浪全市场行情（稳定可用）
  A股备: ak.stock_zh_a_spot_em() — 东方财富全市场行情
  港股:   ak.stock_hk_financial_indicator_em(symbol) — 逐只获取财务指标对比

注意: 新浪接口代码列含市场前缀(sh/sz/bj)，频繁调用会被封IP
      港股对比为逐只获取，速度较慢但数据丰富
"""

import sys
import argparse

sys.path.insert(0, '.')
from _utils import normalize_code, get_market_prefix, output_json, output_error, check_akshare, safe_float, is_hk_code


# A股可对比的指标（东方财富列名）
METRIC_MAP_EM = {
    "pe_ratio": "市盈率-动态",
    "pb_ratio": "市净率",
    "total_market_cap": "总市值",
    "circulating_market_cap": "流通市值",
    "turnover_rate": "换手率",
    "change_pct": "涨跌幅",
    "volume_ratio": "量比",
    "amplitude": "振幅",
}

# A股新浪接口可用的指标
METRIC_MAP_SINA = {
    "change_pct": "涨跌幅",
    "amount": "成交额",
    "high": "最高",
    "low": "最低",
    "open": "今开",
    "prev_close": "昨收",
    "volume": "成交量",
}

# 港股可对比的指标
METRIC_MAP_HK = {
    "pe_ratio": "市盈率",
    "pb_ratio": "市净率",
    "market_cap": "总市值(港元)",
    "roe": "股东权益回报率(%)",
    "net_margin": "销售净利率(%)",
    "net_profit_growth": "净利润滚动环比增长(%)",
    "revenue_growth": "营业总收入滚动环比增长(%)",
    "dividend_yield": "股息率TTM(%)",
}

ALL_A_METRICS = list(METRIC_MAP_EM.keys())
ALL_HK_METRICS = list(METRIC_MAP_HK.keys())


def _fetch_em_batch(codes, metrics):
    """东方财富A股批量获取"""
    import akshare as ak

    df = ak.stock_zh_a_spot_em()
    stocks = []
    for code in codes:
        row = df[df['代码'] == code]
        if row.empty:
            stocks.append({"code": code, "name": "未找到", "error": f"未找到股票代码 {code}"})
            continue

        r = row.iloc[0]
        stock_data = {
            "code": code,
            "name": str(r.get('名称', '')),
            "price": safe_float(r.get('最新价')),
            "change_pct": safe_float(r.get('涨跌幅')),
        }
        for metric_key in metrics:
            col_name = METRIC_MAP_EM.get(metric_key)
            if col_name:
                stock_data[metric_key] = safe_float(r.get(col_name))
        stocks.append(stock_data)
    return stocks, metrics, [METRIC_MAP_EM[m] for m in metrics if m in METRIC_MAP_EM]


def _fetch_sina_batch(codes, metrics):
    """新浪A股批量获取（主接口）"""
    import akshare as ak

    df = ak.stock_zh_a_spot()
    stocks = []
    sina_metrics = [m for m in metrics if m in METRIC_MAP_SINA]
    for code in codes:
        prefix = get_market_prefix(code)
        sina_code = f"{prefix}{code}"
        row = df[df['代码'] == sina_code]
        if row.empty:
            stocks.append({"code": code, "name": "未找到", "error": f"未找到股票代码 {code}"})
            continue

        r = row.iloc[0]
        stock_data = {
            "code": code,
            "name": str(r.get('名称', '')),
            "price": safe_float(r.get('最新价')),
            "change_pct": safe_float(r.get('涨跌幅')),
            "data_source": "sina",
        }
        for metric_key in sina_metrics:
            col_name = METRIC_MAP_SINA.get(metric_key)
            if col_name:
                stock_data[metric_key] = safe_float(r.get(col_name))
        stocks.append(stock_data)
    return stocks, sina_metrics, [METRIC_MAP_SINA[m] for m in sina_metrics if m in METRIC_MAP_SINA]


def _fetch_hk_batch(codes, metrics):
    """港股逐只获取财务指标对比"""
    import akshare as ak

    stocks = []
    hk_metrics = [m for m in metrics if m in METRIC_MAP_HK]
    for code in codes:
        try:
            fi = ak.stock_hk_financial_indicator_em(symbol=code)
            if fi.empty:
                stocks.append({"code": code, "name": "未找到", "error": f"未找到港股 {code}"})
                continue

            r = fi.iloc[0]
            stock_data = {
                "code": code,
                "pe_ratio": safe_float(r.get('市盈率')),
                "pb_ratio": safe_float(r.get('市净率')),
                "market_cap": safe_float(r.get('总市值(港元)')),
                "data_source": "eastmoney_hk",
            }
            for metric_key in hk_metrics:
                col_name = METRIC_MAP_HK.get(metric_key)
                if col_name:
                    stock_data[metric_key] = safe_float(r.get(col_name))
            stocks.append(stock_data)
        except Exception as e:
            stocks.append({"code": code, "error": str(e)})

    return stocks, hk_metrics, [METRIC_MAP_HK[m] for m in hk_metrics if m in METRIC_MAP_HK]


def main():
    parser = argparse.ArgumentParser(description='股票对比分析')
    parser.add_argument('stock_codes', help='股票代码，逗号分隔，如 600519,000858 或 03888,00700')
    parser.add_argument('--metrics', default=None,
                        help='对比指标，逗号分隔（默认全部）')
    args = parser.parse_args()

    err = check_akshare()
    if err:
        output_error(err)
        return

    codes = [normalize_code(c.strip()) for c in args.stock_codes.split(',') if c.strip()]

    if not codes:
        output_error("请提供至少一个股票代码")
        return

    if len(codes) > 10:
        output_error("最多对比10只股票")
        return

    # 自动判断市场类型
    hk_codes = [c for c in codes if is_hk_code(c)]
    a_codes = [c for c in codes if not is_hk_code(c)]

    try:
        import akshare as ak

        # 纯港股对比
        if hk_codes and not a_codes:
            metrics = ALL_HK_METRICS
            if args.metrics:
                metrics = [m.strip() for m in args.metrics.split(',') if m.strip() in METRIC_MAP_HK]

            stocks, used_metrics, metrics_cn = _fetch_hk_batch(hk_codes, metrics)

            data = {
                "market": "HK",
                "stocks": stocks,
                "metrics_compared": used_metrics,
                "metrics_compared_cn": metrics_cn,
            }
            output_json(data)
            return

        # A股对比（含混合情况，只比A股部分）
        if a_codes:
            metrics = ALL_A_METRICS
            if args.metrics:
                metrics = [m.strip() for m in args.metrics.split(',') if m.strip() in METRIC_MAP_EM]

            stocks = None
            used_metrics = metrics
            metrics_cn = []

            try:
                stocks, used_metrics, metrics_cn = _fetch_sina_batch(a_codes, metrics)
            except Exception:
                pass

            if stocks is None:
                try:
                    stocks, used_metrics, metrics_cn = _fetch_em_batch(a_codes, metrics)
                except Exception as e2:
                    output_error(f"股票对比失败: {str(e2)}")
                    return

            # 如果有港股混合，追加港股数据
            if hk_codes:
                hk_metrics = ALL_HK_METRICS
                hk_stocks, hk_used, hk_cn = _fetch_hk_batch(hk_codes, hk_metrics)
                stocks.extend(hk_stocks)
                used_metrics = list(set(used_metrics + hk_used))
                metrics_cn = list(set(metrics_cn + hk_cn))

            data = {
                "stocks": stocks,
                "metrics_compared": used_metrics,
                "metrics_compared_cn": metrics_cn,
            }
            output_json(data)
            return

        output_error("未提供有效的股票代码")

    except Exception as e:
        output_error(f"股票对比失败: {str(e)}")


if __name__ == '__main__':
    main()
