import os
import json
import html
import shutil
from datetime import datetime, timedelta
from urllib.parse import quote
from telegram import Update
from telegram.ext import Application, MessageHandler, filters, ContextTypes

BOT_TOKEN = "8414603233:AAFC7JGtfs00KTrrJFyPooi2fs9TTgIhZ8M"
CHANNEL_ID = "@mehdijabbarifx"
OUT_DIR = "channel_files"
KEEP_DAYS = 2
os.makedirs(OUT_DIR, exist_ok=True)


def window_start():
    now = datetime.now()
    today = now.replace(hour=0, minute=0, second=0, microsecond=0)
    return today - timedelta(days=KEEP_DAYS - 1)


def prune():
    cutoff = window_start().strftime("%Y-%m-%d")
    removed = 0
    for d in os.listdir(OUT_DIR):
        p = os.path.join(OUT_DIR, d)
        if os.path.isdir(p) and d < cutoff:
            shutil.rmtree(p, ignore_errors=True)
            removed += 1
    if removed:
        print(f"پاک شد: {removed} پوشه قدیمی")


def build_index():
    items = []
    cutoff = window_start().strftime("%Y-%m-%d")
    for day in sorted(os.listdir(OUT_DIR), reverse=True):
        if day < cutoff:
            continue
        day_path = os.path.join(OUT_DIR, day)
        if not os.path.isdir(day_path):
            continue
        for msg_id in sorted(os.listdir(day_path), reverse=True):
            msg_path = os.path.join(day_path, msg_id)
            if not os.path.isdir(msg_path):
                continue
            text = ""
            txt_path = os.path.join(msg_path, "message.txt")
            if os.path.isfile(txt_path):
                try:
                    with open(txt_path, "r", encoding="utf-8") as f:
                        text = f.read()
                except Exception:
                    pass
            files = [
                f for f in sorted(os.listdir(msg_path))
                if os.path.isfile(os.path.join(msg_path, f)) and f != "message.txt"
            ]
            items.append({
                "day": day,
                "id": int(msg_id) if msg_id.isdigit() else msg_id,
                "channel": CHANNEL_ID.lstrip("@"),
                "text": text,
                "files": files
            })

    tmp_json = os.path.join(OUT_DIR, "index.tmp.json")
    with open(tmp_json, "w", encoding="utf-8") as f:
        json.dump(items, f, ensure_ascii=False)
    os.replace(tmp_json, os.path.join(OUT_DIR, "index.json"))

    rows = []
    for it in items:
        day = html.escape(str(it["day"]))
        mid = html.escape(str(it["id"]))
        text = html.escape((it["text"] or "")[:120]).replace("\n", " ")
        links = []
        for fn in it["files"]:
            rel = f'{it["day"]}/{it["id"]}/{fn}'
            links.append(f'<a href="{quote(rel)}" target="_blank">{html.escape(fn)}</a>')
        rows.append(f'<tr><td>{day}</td><td>{mid}</td><td>{text}</td><td>{" · ".join(links)}</td></tr>')

    page = f"""<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>آرشیو کانال</title>
<style>
  body {{ font-family: Tahoma, sans-serif; background:#f5f6f8; margin:0; padding:24px; color:#222; }}
  h1 {{ font-size:20px; margin-bottom:16px; }}
  table {{ width:100%; border-collapse:collapse; background:#fff; border-radius:8px; overflow:hidden; }}
  th, td {{ padding:10px 12px; border-bottom:1px solid #eee; text-align:right; font-size:14px; vertical-align:top; }}
  th {{ background:#fafafa; }}
  a {{ color:#1565c0; text-decoration:none; }}
  a:hover {{ text-decoration:underline; }}
</style></head>
<body>
<h1>آرشیو کانال ({len(items)})</h1>
<table>
<tr><th>تاریخ</th><th>شناسه</th><th>متن</th><th>فایل‌ها</th></tr>
{''.join(rows)}
</table>
</body></html>"""
    tmp_html = os.path.join(OUT_DIR, "index.tmp.html")
    with open(tmp_html, "w", encoding="utf-8") as f:
        f.write(page)
    os.replace(tmp_html, os.path.join(OUT_DIR, "index.html"))


async def handle(update: Update, context: ContextTypes.DEFAULT_TYPE):
    msg = update.channel_post or update.effective_message
    if not msg:
        return
    day = datetime.now().strftime("%Y-%m-%d")
    folder = os.path.join(OUT_DIR, day, str(msg.message_id))
    os.makedirs(folder, exist_ok=True)

    text = msg.caption or msg.text or ""
    with open(os.path.join(folder, "message.txt"), "w", encoding="utf-8") as f:
        f.write(text)

    saved = False

    if msg.photo:
        try:
            tg_file = await msg.photo[-1].get_file()
            await tg_file.download_to_drive(os.path.join(folder, "photo.jpg"))
            saved = True
        except Exception as e:
            print(f"خطا در عکس {msg.message_id}: {e}")

    elif msg.animation:
        try:
            tg_file = await msg.animation.get_file()
            ext = ".mp4"
            if msg.animation.file_name and "." in msg.animation.file_name:
                ext = "." + msg.animation.file_name.rsplit(".", 1)[-1]
            await tg_file.download_to_drive(os.path.join(folder, "animation" + ext))
            saved = True
        except Exception as e:
            print(f"خطا در گیف {msg.message_id}: {e}")

    elif msg.video:
        try:
            tg_file = await msg.video.get_file()
            await tg_file.download_to_drive(os.path.join(folder, "video.mp4"))
            saved = True
        except Exception as e:
            print(f"خطا در ویدیو {msg.message_id}: {e}")

    elif msg.document:
        try:
            tg_file = await msg.document.get_file()
            name = msg.document.file_name or f"file_{msg.message_id}"
            await tg_file.download_to_drive(os.path.join(folder, name))
            saved = True
        except Exception as e:
            print(f"خطا در فایل {msg.message_id}: {e}")

    elif msg.sticker:
        try:
            tg_file = await msg.sticker.get_file()
            ext = ".webp"
            if msg.sticker.is_video:
                ext = ".webm"
            elif msg.sticker.is_animated:
                ext = ".tgs"
            await tg_file.download_to_drive(os.path.join(folder, "sticker" + ext))
            saved = True
        except Exception as e:
            print(f"خطا در استیکر {msg.message_id}: {e}")

    elif msg.voice:
        try:
            tg_file = await msg.voice.get_file()
            await tg_file.download_to_drive(os.path.join(folder, "voice.ogg"))
            saved = True
        except Exception as e:
            print(f"خطا در ویس {msg.message_id}: {e}")

    elif msg.video_note:
        try:
            tg_file = await msg.video_note.get_file()
            await tg_file.download_to_drive(os.path.join(folder, "video_note.mp4"))
            saved = True
        except Exception as e:
            print(f"خطا در ویدیو نوت {msg.message_id}: {e}")

    print(f"ذخیره شد: {msg.message_id}" if saved else f"متن ذخیره شد: {msg.message_id}")

    prune()
    build_index()


def main():
    prune()
    build_index()

    app = Application.builder().token(BOT_TOKEN).build()
    app.add_handler(MessageHandler(
        filters.UpdateType.CHANNEL_POST & (
            filters.PHOTO | filters.ANIMATION | filters.VIDEO |
            filters.Document.ALL | filters.TEXT |
            filters.Sticker.ALL | filters.VOICE | filters.VIDEO_NOTE
        ),
        handle
    ))
    app.add_handler(MessageHandler(
        filters.ChatType.PRIVATE & (
            filters.PHOTO | filters.ANIMATION | filters.VIDEO |
            filters.Document.ALL | filters.TEXT |
            filters.Sticker.ALL | filters.VOICE | filters.VIDEO_NOTE
        ),
        handle
    ))
    print("ربات آماده است...")
    app.run_polling(allowed_updates=Update.ALL_TYPES)


if __name__ == "__main__":
    main()