# remottxrea/session/session_health_checker.py

import os
import asyncio

from pyrogram import Client
from pyrogram.errors import (
    Unauthorized,
    UserDeactivated,
    SessionRevoked,
    FloodWait,
    AuthKeyUnregistered
)

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

from ..session.session_data_manager import (
    session_data_manager
)


class SessionHealthChecker:

    # ---------- SINGLE CHECK ----------
    async def check_one(self, phone: str):

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

        result = {
            "phone": phone,
            "status": "UNKNOWN",
            "user_id": None,
            "username": None,
            "error": None
        }

        if not os.path.exists(
            session_path + ".session"
        ):
            result["status"] = "NO_SESSION_FILE"
            return result

        data = session_data_manager.load(phone)

        if not data:
            result["status"] = "NO_DATA_FILE"
            return result

        device = data["device"]

        app = Client(
            name=session_path,
            api_id=API_ID,
            api_hash=API_HASH,

            device_model=device["device_model"],
            system_version=device["system_version"],
            app_version=device["app_version"],
            lang_code=device["lang_code"]
        )

        try:

            await app.connect()

            me = await app.get_me()

            if not me:
                result["status"] = "UNAUTHORIZED"
            else:
                result["status"] = "OK"
                result["user_id"] = me.id
                result["username"] = me.username

        except Unauthorized:
            result["status"] = "UNAUTHORIZED"

        except SessionRevoked:
            result["status"] = "SESSION_REVOKED"

        except AuthKeyUnregistered:
            result["status"] = "AUTHKEY_INVALID"

        except UserDeactivated:
            result["status"] = "DEACTIVATED"

        except FloodWait as e:
            result["status"] = "FLOOD"
            result["error"] = f"Wait {e.value}s"

        except Exception as e:
            result["status"] = "ERROR"
            result["error"] = str(e)

        finally:
            try:
                await app.disconnect()
            except:
                pass

        return result

    # ---------- CHECK ALL ----------
    async def check_all(self):

        phones = []

        for file in os.listdir(SESSIONS_DIR):

            if file.endswith("_data.json"):
                phone = file.replace(
                    "_data.json",
                    ""
                )
                phones.append(phone)

        results = []

        for phone in phones:
            res = await self.check_one(phone)
            results.append(res)

        return results

    # ---------- REMOVE DEAD ----------
    def remove_dead(self, results):

        removed = []

        for r in results:

            if r["status"] != "OK":

                phone = r["phone"]

                session_file = os.path.join(
                    SESSIONS_DIR,
                    phone + ".session"
                )

                data_file = os.path.join(
                    SESSIONS_DIR,
                    phone + "_data.json"
                )

                if os.path.exists(session_file):
                    os.remove(session_file)

                if os.path.exists(data_file):
                    os.remove(data_file)

                removed.append(phone)

        return removed


session_health_checker = SessionHealthChecker()
