#!/usr/bin/env python3
from pathlib import Path
import shutil, datetime, py_compile, sys

BASE = Path("/home/pishvivy/social.pishibini.com")
TARGET = BASE / "engine" / "telegram_publisher.py"

if not TARGET.is_file():
    print("ERROR: telegram_publisher.py not found")
    sys.exit(1)

text = TARGET.read_text(encoding="utf-8")
original = text

backup = TARGET.with_name(
    "telegram_publisher.py.backup_" +
    datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
)
shutil.copy2(TARGET, backup)
print(f"Backup: {backup}")

if "async def send_file_message(" not in text:
    anchor = "async def publish_daily_post("
    if anchor not in text:
        print("ERROR: publish_daily_post anchor not found")
        sys.exit(1)

    fn = """
async def send_file_message(
    publisher_id: int,
    channel_id: int,
    message_file: str
):
    db = get_database()
    client = None

    try:
        publisher = get_publisher(db, publisher_id)
        channel = get_channel(db, channel_id)

        validate_assignment(
            publisher_id,
            publisher,
            channel
        )

        message_path = Path(message_file)

        if not message_path.is_file():
            fail(f"Message file not found: {message_path}")

        message_text = message_path.read_text(
            encoding="utf-8"
        ).strip()

        if not message_text:
            fail("Message text is empty.")

        if len(message_text) > 4096:
            fail("Message exceeds Telegram 4096-character limit.")

        target = resolve_target(channel)

        client = build_client(
            publisher_id,
            publisher
        )

        await ensure_authorized(
            db,
            publisher_id,
            client
        )

        try:
            sent = await client.send_message(
                target,
                message_text
            )
        except FloodWaitError as exc:
            seconds = int(exc.seconds)
            update_flood(db, publisher_id, seconds)
            write_log(
                db,
                publisher_id,
                channel_id,
                "send_file",
                "failed",
                None,
                f"FloodWait: {seconds} seconds"
            )
            fail(f"Telegram FloodWait: {seconds} seconds")

        message_id = str(sent.id)

        clear_flood(db, publisher_id)
        update_publisher_health(
            db,
            publisher_id,
            "healthy",
            None
        )

        write_log(
            db,
            publisher_id,
            channel_id,
            "send_file",
            "success",
            message_id,
            None
        )

        print(
            f"SEND_FILE_SUCCESS message_id={message_id}"
        )

    except SystemExit:
        raise

    except Exception as exc:
        error_text = str(exc)
        try:
            update_publisher_health(
                db,
                publisher_id,
                "error",
                error_text[:2000]
            )
            write_log(
                db,
                publisher_id,
                channel_id,
                "send_file",
                "failed",
                None,
                error_text[:2000]
            )
        except Exception:
            pass
        fail(error_text)

    finally:
        if client is not None:
            try:
                await client.disconnect()
            except Exception:
                pass
        db.close()


"""
    text = text.replace(anchor, fn + anchor, 1)
    print("Patched: send_file_message")

if 'if command == "send_file":' not in text:
    anchor = '    if command == "daily_post":'
    if anchor not in text:
        print("ERROR: daily_post command anchor not found")
        sys.exit(1)

    handler = """
    if command == "send_file":

        if len(sys.argv) < 5:
            fail(
                "Usage:\\n"
                "python3 engine/telegram_publisher.py "
                "send_file <publisher_id> <channel_id> "
                "<message_file>"
            )

        try:
            publisher_id = int(sys.argv[2])
            channel_id = int(sys.argv[3])
        except ValueError:
            fail(
                "Publisher ID and Channel ID must be numeric."
            )

        await send_file_message(
            publisher_id,
            channel_id,
            sys.argv[4]
        )

        return

"""
    text = text.replace(anchor, handler + anchor, 1)
    print("Patched: send_file command")

if text == original:
    print("No changes needed")
    sys.exit(0)

tmp = TARGET.with_suffix(".py.tmp")
tmp.write_text(text, encoding="utf-8")

try:
    py_compile.compile(str(tmp), doraise=True)
except Exception as exc:
    tmp.unlink(missing_ok=True)
    print(f"ERROR: syntax check failed: {exc}")
    sys.exit(1)

tmp.replace(TARGET)
print("telegram_publisher.py patched successfully")
print("Syntax: OK")
print("DONE ✅")
