#!/usr/bin/env python3
"""Read-only search for archive video candidates in existing Telegram sources."""

import asyncio
import re

from telethon import TelegramClient

import fan_news_collector as collector
import telegram_publisher as publisher

SEARCH_TERMS = ("فیگو", "زیدان", "رونالدو", "رئال", "ریال")
MAX_PER_SEARCH = 50
MAX_RESULTS = 20


async def main():
    db = publisher.get_database()
    client = None

    try:
        with db.cursor() as cursor:
            cursor.execute("""
                SELECT telegram_api_id, telegram_api_hash
                FROM publishers
                WHERE is_active = 1
                ORDER BY id
                LIMIT 1
            """)
            credentials = cursor.fetchone()

            cursor.execute("""
                SELECT DISTINCT s.id, s.username
                FROM sources s
                JOIN fan_news_collection_state st
                  ON st.source_id = s.id
                WHERE s.is_active = 1
                  AND s.source_kind = 'telegram'
                  AND s.username IS NOT NULL
                  AND s.username <> ''
                ORDER BY s.id
            """)
            sources = cursor.fetchall()

        if not credentials:
            raise RuntimeError("No active Telegram publisher credentials.")

        collector.ensure_session_copy()

        client = TelegramClient(
            str(collector.FAN_SESSION.with_suffix("")),
            int(str(credentials["telegram_api_id"]).strip()),
            str(credentials["telegram_api_hash"]).strip(),
        )
        await client.connect()

        if not await client.is_user_authorized():
            raise RuntimeError("Fan reader session is not authorized.")

        seen = set()
        found = 0

        for source in sources:
            username = str(source["username"]).strip().lstrip("@")

            try:
                entity = await client.get_entity("@" + username)
            except Exception as exc:
                print(f"SOURCE_SKIPPED @{username}: {type(exc).__name__}")
                continue

            for term in SEARCH_TERMS:
                try:
                    async for message in client.iter_messages(
                        entity, search=term, limit=MAX_PER_SEARCH
                    ):
                        marker = (username.lower(), int(message.id))
                        if marker in seen:
                            continue
                        seen.add(marker)

                        if not message.video:
                            continue

                        caption = re.sub(
                            r"\s+", " ", str(message.message or "")
                        ).strip()

                        # A name alone is not proof of which team's video it is.
                        if not caption:
                            continue

                        print(
                            f"VIDEO source=@{username} "
                            f"message={message.id} "
                            f"date={message.date.date() if message.date else '-'}"
                        )
                        print(f"LINK https://t.me/{username}/{message.id}")
                        print(f"CAPTION {caption[:350]}")
                        print()
                        found += 1

                        if found >= MAX_RESULTS:
                            break
                except Exception as exc:
                    print(
                        f"SEARCH_SKIPPED @{username} {term}: "
                        f"{type(exc).__name__}: {exc}"
                    )

                if found >= MAX_RESULTS:
                    break
            if found >= MAX_RESULTS:
                break

        print(
            f"VIDEO_CANDIDATES={found}; "
            "PREVIEW ONLY — NOTHING DOWNLOADED OR PUBLISHED"
        )
    finally:
        if client:
            await client.disconnect()
        db.close()


if __name__ == "__main__":
    asyncio.run(main())
