from bs4 import BeautifulSoup

import re
from datetime import datetime, date

from .. import models

async def urls_parser(client, cybertalk_url: str):

    now = datetime.now()
    year_month = f"{now.year}-{now.strftime("%B")}"
    today = now.strftime("%Y%m%d")
    base_url = cybertalk_url.format(year_month)
    html = await client.get(f"{base_url}date.html", "koi8-r")
    soup = BeautifulSoup(html, "html.parser")

    result = {"sisyphus": None, "bugs": None, "p11": None}

    for li in soup.find_all("li"):
        a = li.find("a")
        if not a or not a.get("href"):
            continue

        href = a["href"]
        text = a.get_text(strip=True)

        url = base_url + href

        if f"Sisyphus-{today} packages" in text:
            result["sisyphus"] = url
        elif f"Sisyphus-{today} bugs" in text:
            result["bugs"] = url
        elif "p11/branch packages" in text and await _check_date(url, client):
                result["p11"] = url
        elif "p10/branch packages" in text and await _check_date(url, client):
                result["p10"] = url

    return models.NewsURL(**result)


async def urls_for_range(
    client, date_from: date, date_to: date,
    cybertalk_url: str, news_type: str = "packages",
) -> list[tuple[date, str]]:
    results = []
    pattern = re.compile(rf"Sisyphus-(\d{{8}}) {re.escape(news_type)}")

    current = date_from.replace(day=1)
    while current <= date_to:
        year_month = f"{current.year}-{current.strftime('%B')}"
        base_url = cybertalk_url.format(year_month)
        try:
            html = await client.get(f"{base_url}date.html", "koi8-r")
        except:
            current = _next_month(current)
            continue

        soup = BeautifulSoup(html, "html.parser")

        for li in soup.find_all("li"):
            a = li.find("a")
            if not a or not a.get("href"):
                continue
            text = a.get_text(strip=True)
            match = pattern.search(text)
            if match:
                news_date = datetime.strptime(match.group(1), "%Y%m%d").date()
                if date_from <= news_date <= date_to:
                    results.append((news_date, base_url + a["href"]))

        current = _next_month(current)

    return sorted(results)


def _next_month(d: date) -> date:
    if d.month == 12:
        return d.replace(year=d.year + 1, month=1)
    return d.replace(month=d.month + 1)


async def _check_date(url, client):
    html = await client.get(url, "koi8-r")
    soup = BeautifulSoup(html, "html.parser")
    tag = soup.find("i")
    if not tag:
        return False

    parts = tag.text.strip().split()
    if len(parts) < 3:
        return False

    try:
        return int(parts[2]) == datetime.now().day
    except ValueError:
        return False
