# scimkg/core.py
import os
from .processors.video_processor import VideoProcessor
from .processors.pdf_processor import PDFProcessor
from .processors.audio_processor import AudioProcessor
from .processors.concept_extractor import ConceptExtractor
from .processors.subtitle_processor import SubtitleProcessor
from .processors.image_alignment import ImageAlignmentProcessor
from .rdf import TriplesToRDF

class SciMKGProcessor:
    def __init__(self):
        self.video_file = None
        self.pdf_file = None
        self._triples = None
        self._rdf = None
        self.process_id = None

        # Initialize processors
        self.video_processor = VideoProcessor()
        self.pdf_processor = PDFProcessor()
        self.audio_processor = AudioProcessor()
        self.subtitle_processor = SubtitleProcessor()
        self.concept_extractor = ConceptExtractor()
        self.image_alignment_processor = ImageAlignmentProcessor()

    def set_files(self, video_file, pdf_file):
        """设置待处理的输入文件"""
        self.video_file = video_file
        self.pdf_file = pdf_file
        return self

    def set_llm_config(self, api_key=None, base_url=None, model=None):
        """
        设置LLM配置
        
        Args:
            api_key (str): API密钥
            base_url (str): API基础URL
            model (str): 模型名称
        """
        self.concept_extractor.update_config(api_key, base_url, model)
        return self
        
    def set_pdf_api_config(self, api_url):
        """
        设置PDF处理API配置
        
        Args:
            api_url (str): API端点URL
        """
        self.pdf_processor.update_config(api_url)
        return self

    def triples(self):
        """从视频和PDF中提取知识三元组"""
        if self._triples is None:
            self._process_files()
        return self._triples

    def rdf(self):
        """生成知识图谱的RDF表示"""
        if self._rdf is None:
            self._process_files()
        return self._rdf

    def _process_files(self):
        """内部方法处理文件并生成三元组/RDF"""
        if not self.video_file or not self.pdf_file:
            raise ValueError("Video and PDF files must be set before processing")

        # Generate a unique process ID
        import uuid
        self.process_id = str(uuid.uuid4())

        # Process video
        video_results = self.video_processor.process(self.video_file, self.process_id)

        # Process PDF
        pdf_results = self.pdf_processor._extract_images_via_api(self.pdf_file, self.process_id)

        # Extract audio from video
        audio_results = self.audio_processor.extract_audio(self.video_file, self.process_id)

        # Extract concepts
        concepts = self.concept_extractor.extract_concepts(audio_results, None, self.process_id)

        # Convert to triples and RDF
        self._triples = self._convert_to_triples(concepts, video_results, pdf_results)

        # Generate RDF
        rdf_converter = TriplesToRDF()
        rdf_converter.convert_triples_to_rdf(self._triples)
        self._rdf = rdf_converter.graph.serialize(format='xml')

    def _convert_to_triples(self, concepts, video_results, pdf_results):
        """Convert extracted information to knowledge triples"""
        triples = []

        # Add concept triples
        if concepts and 'concepts' in concepts:
            for concept in concepts['concepts']:
                term = concept.get('term', '')
                if term:
                    triples.append((term, "is a", "scientific concept"))

        # Add video triples
        if video_results and 'segments' in video_results:
            for segment in video_results['segments']:
                triples.append((segment['filename'], "is a", "video segment"))

        # Add image triples
        if pdf_results and 'images' in pdf_results:
            for image in pdf_results['images']:
                triples.append((image['filename'], "is an", "educational image"))

        return triples
