# string_session_manager.py

import os

from pyrogram import Client

from config.main_config import (
    API_ID,
    API_HASH,
    SESSIONS_DIR
)


class StringSessionManager:

    # ---------- EXPORT ----------
    async def export(self, phone: str):

        path = os.path.join(SESSIONS_DIR, phone)

        app = Client(
            name=path,
            api_id=API_ID,
            api_hash=API_HASH
        )

        await app.connect()

        session_string = await app.export_session_string()

        await app.disconnect()

        return session_string

    # ---------- IMPORT ----------
    async def import_string(self, phone: str, string_session: str):

        # login with string
        app = Client(
            name=string_session,
            api_id=API_ID,
            api_hash=API_HASH,
            in_memory=True
        )

        await app.connect()

        if not await app.get_me():
            return False

        # save as file session
        file_path = os.path.join(SESSIONS_DIR, phone)

        file_app = Client(
            name=file_path,
            api_id=API_ID,
            api_hash=API_HASH
        )

        await file_app.connect()

        exported = await app.export_session_string()

        await file_app.stop()

        # recreate file session
        save_app = Client(
            name=file_path,
            api_id=API_ID,
            api_hash=API_HASH,
            session_string=exported
        )

        await save_app.start()
        await save_app.stop()

        await app.disconnect()

        return True
