from __future__ import annotations

import os
from typing import Optional

import requests

from .types import PlayItem


def head_ok(url: str, session: requests.Session) -> bool:
    try:
        r = session.head(url, allow_redirects=True, timeout=15)
        return r.status_code in (200, 206)
    except requests.RequestException:
        return False


def select_audio_url(
    item: PlayItem,
    base_url: str,
    session: requests.Session,
    *,
    no_head: bool,
    seen_urls: set[str],
) -> Optional[str]:
    for mp3_path in item.mp3_paths:
        url = f"{base_url}/{mp3_path}"
        if url in seen_urls:
            continue
        if no_head or head_ok(url, session):
            return url
    return None


def download_audio(url: str, out_path: str, session: requests.Session) -> None:
    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    with session.get(url, stream=True, timeout=30) as r:
        r.raise_for_status()
        with open(out_path, "wb") as f:
            for chunk in r.iter_content(chunk_size=1024 * 128):
                if chunk:
                    f.write(chunk)
