"""
Bio Change Handler

Features:
- Multi-session dispatch
- Live progress stream
- Execution report
- Logger integrated
- Error isolation
"""

from ...actions.change_bio import (
    BioChanger
)

from ...core.logger import (
    get_action_logger
)


class ChangeBioHandler:

    def __init__(self, runner):
        self.runner = runner

    # ---------------------------------
    async def handle(self, message):

        text = message.text.strip()

        # ---------- PARSE INPUT ----------
        try:

            bio_text = text.split(
                " ",
                1
            )[1]

        except IndexError:

            return await message.reply_text(
                "Usage:\nbio Hello world"
            )

        # ---------- PROGRESS MESSAGE ----------
        progress = await message.reply_text(
            "Starting bio update..."
        )

        # ---------- ACTION ----------
        async def action(phone, app):

            logger = get_action_logger(
                action="change_bio",
                session=phone
            )

            changer = BioChanger(
                app,
                phone
            )

            try:

                await changer.change(
                    bio_text
                )

                logger.info(
                    f"Bio updated → {bio_text}"
                )

                return True

            except Exception as e:

                logger.exception(
                    f"Bio change failed → {e}"
                )

                raise e

        # ---------- RUN ----------
        tracker = await self.runner.run_action(
            action_func=action,
            progress_message=progress
        )

        # ---------- FINAL REPORT ----------
        report = tracker.summary_text()

        await message.reply_text(
            report
        )
