"""
股票财务数据查询

用法: python stock_financial.py <stock_code> [--report <type>] [--count <n>]
  stock_code: 6位A股代码(如 600519) 或 5位港股代码(如 03888)
  --report:   报表类型 income/balance/cashflow，默认income
  --count:    报告期数，默认4

AKShare接口:
  A股:   ak.stock_financial_report_sina(stock, symbol) — 新浪完整多期报表
  港股补: ak.stock_hk_financial_indicator_em(symbol) — 东方财富关键财务指标
  港股补: ak.stock_hk_dividend_payout_em(symbol) — 东方财富分红派息历史
  港股补: ak.stock_hk_valuation_comparison_em(symbol) — 东方财富估值行业对比
  港股补: ak.stock_hk_growth_comparison_em(symbol) — 东方财富成长性行业对比
"""

import sys
import argparse

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


REPORT_MAP = {
    "income": "利润表",
    "balance": "资产负债表",
    "cashflow": "现金流量表",
}


def _fetch_hk_financial(code):
    """港股财务数据：指标+分红+估值对比+成长对比"""
    import akshare as ak

    result = {
        "code": code,
        "report_type": "hk_comprehensive",
        "report_type_cn": "港股综合财务",
        "data_source": "eastmoney_hk",
    }

    # 1. 关键财务指标
    try:
        fi = ak.stock_hk_financial_indicator_em(symbol=code)
        if not fi.empty:
            r = fi.iloc[0]
            result["indicators"] = {
                "eps": safe_float(r.get('基本每股收益(元)')),
                "bps": safe_float(r.get('每股净资产(元)')),
                "dividend_per_share_ttm": safe_float(r.get('每股股息TTM(港元)')),
                "payout_ratio": safe_float(r.get('派息比率(%)')),
                "dividend_yield_ttm": safe_float(r.get('股息率TTM(%)')),
                "revenue": safe_float(r.get('营业总收入')),
                "revenue_growth": safe_float(r.get('营业总收入滚动环比增长(%)')),
                "net_profit": safe_float(r.get('净利润')),
                "net_profit_growth": safe_float(r.get('净利润滚动环比增长(%)')),
                "net_margin": safe_float(r.get('销售净利率(%)')),
                "roe": safe_float(r.get('股东权益回报率(%)')),
                "roa": safe_float(r.get('总资产回报率(%)')),
                "pe": safe_float(r.get('市盈率')),
                "pb": safe_float(r.get('市净率')),
                "market_cap": safe_float(r.get('总市值(港元)')),
                "shares_outstanding": safe_float(r.get('已发行股本(股)')),
            }
        else:
            result["indicators"] = None
            result["indicators_error"] = "东方财富港股指标接口返回空数据"
    except Exception as e:
        result["indicators"] = None
        result["indicators_error"] = f"获取关键指标失败: {str(e)}"

    # 2. 分红派息历史
    try:
        div_df = ak.stock_hk_dividend_payout_em(symbol=code)
        if not div_df.empty:
            dividends = []
            for _, row in div_df.head(5).iterrows():
                dividends.append({
                    "announce_date": str(row.get('最新公告日期', '')),
                    "fiscal_year": str(row.get('财政年度', '')),
                    "plan": str(row.get('分红方案', '')),
                    "type": str(row.get('分配类型', '')),
                    "ex_date": str(row.get('除净日', '')),
                    "pay_date": str(row.get('发放日', '')),
                })
            result["dividends"] = dividends
            result["dividend_count"] = len(dividends)
        else:
            result["dividends"] = []
            result["dividends_error"] = "分红派息接口返回空数据"
    except Exception as e:
        result["dividends"] = []
        result["dividends_error"] = f"获取分红数据失败: {str(e)}"

    # 3. 估值行业对比
    try:
        val_df = ak.stock_hk_valuation_comparison_em(symbol=code)
        if not val_df.empty:
            r = val_df.iloc[0]
            result["valuation_comparison"] = {
                "pe_ttm": safe_float(r.get('市盈率-TTM')),
                "pe_ttm_rank": safe_float(r.get('市盈率-TTM排名')),
                "pe_lyr": safe_float(r.get('市盈率-LYR')),
                "pb_mrq": safe_float(r.get('市净率-MRQ')),
                "pb_mrq_rank": safe_float(r.get('市净率-MRQ排名')),
                "ps_ttm": safe_float(r.get('市销率-TTM')),
                "ps_ttm_rank": safe_float(r.get('市销率-TTM排名')),
            }
        else:
            result["valuation_comparison"] = None
            result["valuation_comparison_error"] = "估值对比接口返回空数据"
    except Exception as e:
        result["valuation_comparison"] = None
        result["valuation_comparison_error"] = f"获取估值对比失败: {str(e)}"

    # 4. 成长性行业对比
    try:
        grow_df = ak.stock_hk_growth_comparison_em(symbol=code)
        if not grow_df.empty:
            r = grow_df.iloc[0]
            result["growth_comparison"] = {
                "eps_growth": safe_float(r.get('基本每股收益同比增长率')),
                "eps_growth_rank": safe_float(r.get('基本每股收益同比增长率排名')),
                "revenue_growth": safe_float(r.get('营业收入同比增长率')),
                "revenue_growth_rank": safe_float(r.get('营业收入同比增长率排名')),
                "op_profit_growth": safe_float(r.get('营业利润率同比增长率')),
                "op_profit_growth_rank": safe_float(r.get('营业利润率同比增长率排名')),
            }
        else:
            result["growth_comparison"] = None
            result["growth_comparison_error"] = "成长性对比接口返回空数据"
    except Exception as e:
        result["growth_comparison"] = None
        result["growth_comparison_error"] = f"获取成长性对比失败: {str(e)}"

    return result


def main():
    parser = argparse.ArgumentParser(description='股票财务数据查询')
    parser.add_argument('stock_code', help='股票代码')
    parser.add_argument('--report', default='income', choices=REPORT_MAP.keys(),
                        help='报表类型: income/balance/cashflow')
    parser.add_argument('--count', type=int, default=4, help='报告期数(默认4)')
    args = parser.parse_args()

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

    code = normalize_code(args.stock_code)
    report_cn = REPORT_MAP[args.report]

    try:
        import akshare as ak

        # 港股：综合财务数据
        if is_hk_code(code):
            data = _fetch_hk_financial(code)
            if data.get("indicators") is None and not data.get("dividends"):
                output_error(f"未找到港股 {code} 的财务数据")
                return
            output_json(data)
            return

        # A股：新浪财务报表
        df = None
        try:
            df = ak.stock_financial_report_sina(stock=code, symbol=report_cn)
        except (TypeError, KeyError, AttributeError):
            pass

        if df is None or df.empty:
            output_error(f"未找到 {code} 的{report_cn}数据，该接口仅支持A股")
            return

        # 取前N期
        df = df.head(args.count)

        # 转为字典列表，处理NaN
        periods = []
        for _, row in df.iterrows():
            period_data = {}
            for col in df.columns:
                val = row[col]
                if str(val) == 'nan':
                    period_data[col] = None
                else:
                    period_data[col] = safe_float(val, str(val))
            periods.append(period_data)

        # 获取股票名称
        name = periods[0].get('股票代码', code) if periods else code

        data = {
            "code": code,
            "name": name,
            "report_type": args.report,
            "report_type_cn": report_cn,
            "periods": periods,
        }

        output_json(data)

    except Exception as e:
        output_error(f"获取财务数据失败: {str(e)}")


if __name__ == '__main__':
    main()
