"""
财务报表解析器命令行接口
"""

import argparse
import sys
import logging
from pathlib import Path
from typing import Optional

from .parser import FinancialReportParser
from .utils import validate_file


def setup_logging(verbose: bool = False) -> None:
    """设置日志配置"""
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(
        level=level,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )


def parse_args() -> argparse.Namespace:
    """解析命令行参数"""
    parser = argparse.ArgumentParser(
        description="财务报表解析器",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例用法:
  %(prog)s parse report.pdf
  %(prog)s parse report.xlsx --output result.json
  %(prog)s --version
        """
    )
    
    parser.add_argument(
        'command',
        choices=['parse'],
        help='要执行的命令'
    )
    
    parser.add_argument(
        'file',
        help='要解析的文件路径'
    )
    
    parser.add_argument(
        '--output', '-o',
        help='输出文件路径 (默认输出到控制台)'
    )
    
    parser.add_argument(
        '--verbose', '-v',
        action='store_true',
        help='显示详细日志'
    )
    
    parser.add_argument(
        '--version',
        action='version',
        version='%(prog)s 0.1.0'
    )
    
    return parser.parse_args()


def main() -> int:
    """主函数"""
    args = parse_args()
    setup_logging(args.verbose)
    
    logger = logging.getLogger(__name__)
    
    try:
        # 验证文件
        if not validate_file(args.file):
            logger.error(f"不支持的文件格式: {args.file}")
            return 1
        
        # 创建解析器
        parser = FinancialReportParser()
        
        # 执行解析
        if args.command == 'parse':
            result = parser.parse_pdf(args.file)
            
            # 输出结果
            if args.output:
                import json
                with open(args.output, 'w', encoding='utf-8') as f:
                    json.dump(result, f, ensure_ascii=False, indent=2)
                logger.info(f"结果已保存到: {args.output}")
            else:
                import json
                print(json.dumps(result, ensure_ascii=False, indent=2))
        
        return 0
        
    except Exception as e:
        logger.error(f"解析失败: {e}")
        return 1


if __name__ == '__main__':
    sys.exit(main()) 