#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
人民日报热点排行爬虫命令行工具
用法: python RmrbHotPoint.py
"""

import argparse
import json
import sys
from pathlib import Path

# Add parent directory to path to import crawler
sys.path.insert(0, str(Path(__file__).parent.parent))

from crawler.RmrbCrawler import RmrbCrawler
from loguru import logger


def main():
    """主函数"""
    parser = argparse.ArgumentParser(
        description='人民日报热点排行获取工具',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  python RmrbHotPoint.py
  python RmrbHotPoint.py --output "output/hotpoint.json"
        """
    )

    # 添加输出文件参数
    parser.add_argument(
        '--output', '-o',
        type=str,
        help='输出文件路径'
    )

    args = parser.parse_args()

    output_file = args.output
    logger.info("使用直接参数模式")

    try:
        logger.info("开始获取人民日报热点排行")
        crawler = RmrbCrawler()
        result = crawler.hotPointRank()

        output = {
            "code": result.code,
            "message": result.message,
            "success": result.success,
            "data": None,
            "dataList": [item.model_dump() for item in result.dataList] if result.dataList else []
        }

        if output_file:
            output_path = Path(output_file)
            output_path.parent.mkdir(parents=True, exist_ok=True)
            with open(output_path, 'w', encoding='utf-8') as f:
                json.dump(output, f, ensure_ascii=False, indent=2)
            logger.info(f"结果已保存到: {output_file}")

        print(json.dumps(output, ensure_ascii=False, indent=2))
        crawler.close()
        sys.exit(0 if result.success else 1)

    except Exception as e:
        logger.error(f"执行失败: {str(e)}")
        error_output = {
            "code": 500,
            "message": f"执行失败: {str(e)}",
            "success": False,
            "data": None,
            "dataList": []
        }
        print(json.dumps(error_output, ensure_ascii=False, indent=2))
        sys.exit(1)


if __name__ == "__main__":
    main()