import time
from state import load_state, save_state
from vk_playlist import get_playlist_videos
from downloader import download_audio, get_video_title
from telegram_sender import send_audio, send_message

CHECK_INTERVAL = 300  # seconds


def process_new_video(video_id, video_url, known_ids):
    try:
        title = get_video_title(video_url)

        print("New podcast detected:", title)
        send_message(f"New podcast: {title}")

        file_path, _ = download_audio(video_url)

        print("Sending audio:", title)
        ok = send_audio(file_path, title)

        if ok:
            print("Upload completed:", title)
            known_ids.add(video_id)
            save_state(known_ids)
        else:
            print("Upload failed — will retry later")

    except Exception as e:
        print("Failed processing:", e)


def run_once():
    known_ids, has_state = load_state()

    videos = get_playlist_videos()
    current_ids = set(videos.keys())

    # first launch — remember everything
    if not has_state:
        print("First run: indexing playlist only")
        save_state(current_ids)
        return

    new_ids = current_ids - known_ids

    if new_ids:
        print(f"Found {len(new_ids)} new videos")

    for vid in new_ids:
        process_new_video(vid, videos[vid], known_ids)


def main_loop():
    while True:
        try:
            print("Checking playlist...")
            run_once()
        except Exception as e:
            print("Loop error:", e)

        time.sleep(CHECK_INTERVAL)


if __name__ == "__main__":
    main_loop()
