from .registry_functions import *
class infoRegistry(metaclass=SingletonMeta):
    def __init__(self,video_root=None, documents_root=None, flat_layout: bool = False, **kwargs):
        if not hasattr(self, "initialized"):
            self.initialized = True
            self.engine = engine
            self.videos_root = video_root or get_videos_root()
    def _upsert(self, video_id, data: dict):
        stmt = insert(VIDEOSTABLE).values(video_id=video_id, info=data)
        stmt = stmt.on_conflict_do_update(
            index_elements=["video_id"],
            set_={"info": data, "updated_at": text("NOW()")}
        )
        with self.engine.begin() as conn:
            conn.execute(stmt)

    def get_video_info(self, url=None, video_id=None, video_path=None, force_refresh=False):
        url = get_corrected_url(url)
        if not video_id:
            if url:
                video_id = get_video_id(url)
            elif video_path:
                video_id = generate_video_id(video_path)
        
        with self.engine.begin() as conn:
            row = conn.execute(VIDEOSTABLE.select().where(VIDEOSTABLE.c.video_id == video_id)).first()
            if row and not force_refresh:
                return dict(row._mapping)
   
        info = get_yt_dlp_info(url) if url else {}
        info_video_id = info.get('video_id')
        video_id =  video_id or info_video_id
        if info_video_id != video_id:
            info['video_id'] = video_id
        info = ensure_standard_paths(
            info,
            video_id=video_id,
            root_dir=self.videos_root,
            video_url=url,
            video_path=video_path
            )
        if info:
            self._upsert(video_id, info)
            return {"video_id": video_id, "info": info}
        return None

    def edit_info(self, data, video_id=None, url=None, video_path=None):
        if not video_id:
            video_id = get_video_id(url) if url else generate_video_id(video_path)
        self._upsert(video_id, data)
        return self.get_video_info(video_id=video_id, force_refresh=True)
