# remottxrea/actions/account_overview.py

import asyncio
from datetime import datetime, timezone
from typing import Dict, List

from pyrogram.errors import (
    FloodWait,
    RPCError,
    AuthKeyUnregistered,
)

from runner.multi_session_runner import (
    MultiSessionRunner
)


MAX_CONCURRENT = 5


class AccountOverview:

    def __init__(self, runner: MultiSessionRunner):
        self.runner = runner
        self.semaphore = asyncio.Semaphore(MAX_CONCURRENT)

    # ======================================================
    async def run(self) -> str:
        """
        Inspect all loaded sessions from MultiSessionRunner
        """

        # گرفتن snapshot ایمن از client ها
        async with self.runner._lock:
            clients = list(self.runner.clients.items())

        if not clients:
            return "No sessions loaded."

        tasks = [
            self._inspect_single(phone, app)
            for phone, app in clients
        ]

        results = await asyncio.gather(*tasks)

        # ---- sort by last seen (newest first) ----
        results.sort(
            key=lambda r: r["last_seen_ts"] or 0,
            reverse=True
        )

        return self._format_table(results)

    # ======================================================
    async def _inspect_single(self, phone, app) -> Dict:

        async with self.semaphore:

            result = {
                "phone": phone,
                "valid": False,
                "active": False,
                "last_seen": "-",
                "last_seen_ts": None,
                "flood": False,
                "error": "-"
            }

            try:
                # ---- ensure running ----
                if not app.is_connected:
                    await app.start()

                result["active"] = True

                me = await app.get_me()
                result["valid"] = True

                now = datetime.now(timezone.utc)

                if me.status:
                    status = me.status

                    if hasattr(status, "was_online"):
                        ts = status.was_online
                        result["last_seen_ts"] = ts.timestamp()
                        result["last_seen"] = ts.strftime("%Y-%m-%d %H:%M")

                    elif hasattr(status, "expires"):
                        result["last_seen"] = "Online"
                        result["last_seen_ts"] = now.timestamp()

            except FloodWait as e:
                result["flood"] = True
                result["error"] = f"Flood {e.value}s"

            except AuthKeyUnregistered:
                result["error"] = "Invalid Session"

            except RPCError as e:
                result["error"] = str(e)

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

            return result

    # ======================================================
    def _format_table(self, results: List[Dict]) -> str:

        header = (
            f"{'PHONE':<15}"
            f"{'VALID':<8}"
            f"{'ACTIVE':<8}"
            f"{'LAST SEEN':<20}"
            f"{'FLOOD':<8}"
            f"{'ERROR'}"
        )

        separator = "-" * 100
        lines = [header, separator]

        for r in results:
            line = (
                f"{r['phone']:<15}"
                f"{str(r['valid']):<8}"
                f"{str(r['active']):<8}"
                f"{r['last_seen']:<20}"
                f"{str(r['flood']):<8}"
                f"{r['error']}"
            )
            lines.append(line)

        return "\n".join(lines)