import os
import asyncio
import subprocess
import contextlib
import contextvars
from typing import *

import wait4it
import sqlmodel
from sqlmodel import Session
from aioify import aioify

from twitterscraper.models.domain import TwitterProfile, TwitterTweet, JobHistoric
from twitterscraper.utils import Singleton


class Repository(Singleton):
    # https://sqlmodel.tiangolo.com/
    get: Callable[..., "Repository"]
    _session_contextvar: contextvars.ContextVar[Optional[Session]]

    def __init__(self, uri: str):
        self._engine = sqlmodel.create_engine(uri)
        self._session_contextvar = contextvars.ContextVar("session", default=None)
        # TODO implement pool_pre_ping & pool_recycle_time

        # Fix for https://github.com/tiangolo/sqlmodel/issues/189#issuecomment-1025190094
        from sqlmodel.sql.expression import Select, SelectOfScalar
        SelectOfScalar.inherit_cache = True  # type: ignore
        Select.inherit_cache = True  # type: ignore

    def _new_session(self) -> Session:
        session = 