"""
Telegram Telethon Service
Uses your personal Telegram account (via mysession.session) to:
  - List all groups/channels you are a member of
  - Send messages to selected groups
Ported from telegarammsg/main.py
"""
import asyncio
from typing import List, Dict, Any, Optional
from app.config import settings

# Telethon client is created once and reused across requests
_client = None


def get_client():
    """Return the singleton Telethon client."""
    global _client
    if _client is None:
        try:
            from telethon import TelegramClient
            _client = TelegramClient(
                "mysession",  # session file in the CWD (automation_platform/)
                settings.TELEGRAM_API_ID,
                settings.TELEGRAM_API_HASH,
            )
        except ImportError:
            raise ImportError("telethon is not installed. Run: pip install telethon")
    return _client


async def start_telethon():
    """Start the Telethon client (called on app startup)."""
    client = get_client()
    if not client.is_connected():
        await client.connect()
        if not await client.is_user_authorized():
            print("⚠️  Telegram session not authorized. Session file may be missing.")
        else:
            print("✅ Telegram Telethon client connected.")


async def stop_telethon():
    """Disconnect the Telethon client (called on app shutdown)."""
    global _client
    if _client and _client.is_connected():
        await _client.disconnect()
        print("❌ Telegram Telethon client disconnected.")
    _client = None


async def list_groups() -> List[Dict[str, Any]]:
    """Return all groups and channels the user is a member of."""
    client = get_client()
    if not client.is_connected():
        await client.connect()

    groups = []
    try:
        async for dialog in client.iter_dialogs():
            if dialog.is_group or dialog.is_channel:
                groups.append({
                    "id": dialog.id,
                    "name": dialog.name,
                    "type": "channel" if dialog.is_channel else "group",
                    "unread": dialog.unread_count,
                })
    except Exception as e:
        print(f"Error listing Telegram groups: {e}")

    return groups


async def send_to_groups(group_ids: List[int], message: str) -> Dict[str, Any]:
    """Send a message to each of the specified group IDs."""
    client = get_client()
    if not client.is_connected():
        await client.connect()

    results = []
    errors = []

    for gid in group_ids:
        try:
            await client.send_message(int(gid), message)
            await asyncio.sleep(1)  # avoid flood-wait
            results.append({"group_id": gid, "status": "sent"})
        except Exception as e:
            errors.append({"group_id": gid, "error": str(e)})

    return {
        "sent": len(results),
        "failed": len(errors),
        "results": results,
        "errors": errors,
    }
