from typing import Optional, Dict, Any


class CrawlResult:
    """通用爬取结果模型"""
    
    def __init__(self,
                 resource_id: str,
                 url: str,
                 success: bool = False,
                 error: str = '',
                 content: str = '',
                 content_parsed: Dict[str, Any] = None):
        """
        初始化爬取结果
        
        Args:
            resource_id: 资源名称
            url: 链接
            success: 是否成功
            error: 错误信息
            content: 原始内容
            content_parsed: 解析后的内容（json格式）
        """
        self.resource_id = resource_id
        self.url = url
        self.success = success
        self.error = error
        self.content = content
        self.content_parsed = content_parsed or {}
    
    def to_dict(self) -> Dict[str, Any]:
        """
        转换为字典
        
        Returns:
            字典形式的爬取结果
        """
        return {
            'resource_id': self.resource_id,
            'url': self.url,
            'success': self.success,
            'error': self.error,
            'content': self.content,
            'content_parsed': self.content_parsed
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'CrawlResult':
        """
        从字典创建实例
        
        Args:
            data: 字典数据
            
        Returns:
            爬取结果实例
        """
        return cls(
            resource_id=data.get('resource_id', ''),
            url=data.get('url', ''),
            success=data.get('success', False),
            error=data.get('error', ''),
            content=data.get('content', ''),
            content_parsed=data.get('content_parsed', {})
        )