import json
import logging
import shutil
import asyncio
import fcntl
from datetime import datetime, timezone
from pathlib import Path

from aiogram import Bot
from aiogram.types import FSInputFile

from app.config import BOT_TOKEN, TEMP_DIR, MAX_OUTPUT_MB
from database.db import init_db, get_next_job, update_job
from engine.cli import download_raw
from archive.zip_builder import zip_tree, zip_chapter_dirs, safe_name

ROOT = Path(__file__).resolve().parents[1]
logging.basicConfig(
    filename=ROOT / "logs" / "worker.log",
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
)

def make_combined(job, work):
    raw = work / "raw"
    raw.mkdir(parents=True, exist_ok=True)
    numbers = [str(ch["number"]) for ch in job["chapters"]]
    download_raw(job["manga_url"], numbers, raw, bundle=False)
    output = work / f"{safe_name(job['title'])}.zip"
    zip_tree(raw, output, root_name=safe_name(job["title"]))
    return [output]

def make_separate(job, work):
    results = []
    for index, chapter in enumerate(job["chapters"], 1):
        raw = work / f"chapter_{index:03d}"
        raw.mkdir(parents=True, exist_ok=True)
        download_raw(job["manga_url"], [str(chapter["number"])], raw, bundle=False)
        chapter_zips = zip_chapter_dirs(raw, work / f"zips_{index:03d}", job["title"])
        for item_no, archive_path in enumerate(chapter_zips, 1):
            renamed = archive_path.with_name(f"Chapter_{index:03d}_{item_no:02d}_{archive_path.name}")
            archive_path.rename(renamed)
            results.append(renamed)
    return results

async def send_results(job, files):
    bot = Bot(BOT_TOKEN)
    try:
        for file_path in files:
            size = file_path.stat().st_size
            if size > MAX_OUTPUT_MB * 1024 * 1024:
                await bot.send_message(
                    job["user_id"],
                    f"⚠️ فایل {file_path.name} از سقف ارسال تنظیم‌شده ({MAX_OUTPUT_MB}MB) بزرگ‌تر است."
                )
                continue
            await bot.send_document(
                job["user_id"],
                document=FSInputFile(str(file_path)),
                caption=f"📚 {job['title']}\\nدرخواست #{job['id']}\\n{file_path.name}",
            )
    finally:
        await bot.session.close()

def _process_one_locked():
    init_db()
    job = get_next_job()
    if not job:
        logging.info("No queued jobs")
        return False

    work = TEMP_DIR / f"job_{job['id']}"
    try:
        if work.exists():
            shutil.rmtree(work, ignore_errors=True)
        work.mkdir(parents=True)
        update_job(job["id"], progress="در حال دانلود")
        files = make_combined(job, work) if job["output_mode"] == "combined" else make_separate(job, work)
        if not files:
            raise RuntimeError("هیچ فایل خروجی ساخته نشد.")
        update_job(job["id"], progress="در حال ارسال")
        asyncio.run(send_results(job, files))
        update_job(
            job["id"], status="done", progress="تکمیل شد",
            finished_at=datetime.now(timezone.utc).isoformat(),
            files_json=json.dumps([p.name for p in files], ensure_ascii=False),
        )
        logging.info("Job %s completed", job["id"])
    except Exception as exc:
        logging.exception("Job %s failed", job["id"])
        update_job(
            job["id"], status="failed", error=str(exc)[:3000], progress="ناموفق",
            finished_at=datetime.now(timezone.utc).isoformat(),
        )
        if BOT_TOKEN:
            async def notify():
                bot = Bot(BOT_TOKEN)
                try:
                    await bot.send_message(job["user_id"], f"❌ درخواست #{job['id']} ناموفق بود:\\n{str(exc)[:1000]}")
                finally:
                    await bot.session.close()
            try:
                asyncio.run(notify())
            except Exception:
                logging.exception("Could not notify user")
    finally:
        shutil.rmtree(work, ignore_errors=True)
    return True

def process_one():
    lock_path = ROOT / "storage" / "worker.lock"
    lock_path.parent.mkdir(parents=True, exist_ok=True)
    with open(lock_path, "w") as lock_file:
        try:
            fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            logging.info("Another worker is already running")
            return False
        try:
            return _process_one_locked()
        finally:
            fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)

if __name__ == "__main__":
    process_one()
