"""
股票新闻/公司资讯查询

用法: python stock_news.py <stock_code> [--count <n>]
  stock_code: 6位A股代码(如 600519) 或 5位港股代码(如 03888)
  --count:    新闻条数，默认10

AKShare接口:
  A股:   ak.stock_news_em(symbol) — 东方财富个股新闻
  港股:  ak.stock_hk_company_profile_em(symbol) — 东方财富公司资料(港股无新闻接口)
  港股:  ak.stock_hk_security_profile_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


def _fetch_hk_profile(code):
    """港股公司资料（替代新闻）"""
    import akshare as ak

    data = {"code": code, "type": "hk_company_profile"}

    # 公司资料
    try:
        profile = ak.stock_hk_company_profile_em(symbol=code)
        if not profile.empty:
            p = profile.iloc[0]
            data["company"] = {
                "name": str(p.get('公司名称', '')),
                "name_en": str(p.get('英文名称', '')),
                "industry": str(p.get('所属行业', '')),
                "chairman": str(p.get('董事长', '')),
                "employees": safe_float(p.get('员工人数')),
                "website": str(p.get('公司网址', '')),
                "founded": str(p.get('公司成立日期', '')),
                "description": str(p.get('公司介绍', ''))[:500],
            }
    except Exception:
        data["company"] = None

    # 证券资料
    try:
        sec = ak.stock_hk_security_profile_em(symbol=code)
        if not sec.empty:
            s = sec.iloc[0]
            data["security"] = {
                "name": str(s.get('证券简称', '')),
                "list_date": str(s.get('上市日期', '')),
                "type": str(s.get('证券类型', '')),
                "board": str(s.get('板块', '')),
                "ipo_price": safe_float(s.get('发行价')),
                "lot_size": safe_float(s.get('每手股数')),
                "exchange": str(s.get('交易所', '')),
                "is_sh_hkconnect": str(s.get('是否沪港通标的', '')),
                "is_sz_hkconnect": str(s.get('是否深港通标的', '')),
            }
    except Exception:
        data["security"] = None

    return data


def main():
    parser = argparse.ArgumentParser(description='股票新闻/公司资讯查询')
    parser.add_argument('stock_code', help='股票代码')
    parser.add_argument('--count', type=int, default=10, help='新闻条数(默认10)')
    args = parser.parse_args()

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

    code = normalize_code(args.stock_code)

    try:
        import akshare as ak

        # 港股：先尝试东方财富新闻接口，失败则返回公司资料
        if is_hk_code(code):
            # 1. 尝试东方财富新闻（已支持港股代码）
            try:
                df = ak.stock_news_em(symbol=code)
                if df is not None and not df.empty:
                    df = df.head(args.count * 3)
                    seen = set()
                    news_items = []
                    for _, row in df.iterrows():
                        title = str(row.get('新闻标题', ''))
                        url = str(row.get('新闻链接', ''))
                        dedup_key = (title.strip(), url.strip())
                        if dedup_key in seen:
                            continue
                        seen.add(dedup_key)
                        item = {
                            "title": title,
                            "content": str(row.get('新闻内容', ''))[:200],
                            "source": str(row.get('文章来源', '')),
                            "publish_time": str(row.get('发布时间', '')),
                            "url": url,
                        }
                        news_items.append(item)
                        if len(news_items) >= args.count:
                            break

                    data = {
                        "code": code,
                        "type": "hk_news",
                        "news_count": len(news_items),
                        "news": news_items,
                    }
                    # 同时获取公司资料作为补充
                    profile_data = _fetch_hk_profile(code)
                    if profile_data.get("company"):
                        data["company"] = profile_data["company"]
                    if profile_data.get("security"):
                        data["security"] = profile_data["security"]
                    output_json(data)
                    return
            except Exception:
                pass

            # 2. 新闻接口失败，回退到公司资料
            data = _fetch_hk_profile(code)
            data["type"] = "hk_company_profile"
            data["news_note"] = "东方财富新闻接口暂不可用，仅返回公司资料"
            if data.get("company") is None and data.get("security") is None:
                output_error(f"未找到港股 {code} 的公司资料")
                return
            output_json(data)
            return

        # A股：东方财富新闻
        df = ak.stock_news_em(symbol=code)

        if df.empty:
            output_error(f"未找到 {code} 的新闻数据")
            return

        df = df.head(args.count * 3)  # 取更多以应对去重后不足

        seen = set()
        news_items = []
        for _, row in df.iterrows():
            title = str(row.get('新闻标题', ''))
            url = str(row.get('新闻链接', ''))
            # 去重：标题+链接组合唯一
            dedup_key = (title.strip(), url.strip())
            if dedup_key in seen:
                continue
            seen.add(dedup_key)

            item = {
                "title": title,
                "content": str(row.get('新闻内容', ''))[:200],
                "source": str(row.get('文章来源', '')),
                "publish_time": str(row.get('发布时间', '')),
                "url": url,
            }
            news_items.append(item)
            if len(news_items) >= args.count:
                break

        data = {
            "code": code,
            "news_count": len(news_items),
            "news": news_items,
        }

        output_json(data)

    except Exception as e:
        output_error(f"获取新闻失败: {str(e)}")


if __name__ == '__main__':
    main()
