import requests
from bs4 import BeautifulSoup

SUBJECT_URL = "https://subject.ktunotes.live/{}"

HEADERS = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36"
}


def fetch_drive_link(subject_code):
    url = SUBJECT_URL.format(subject_code.lower())
    resp = requests.get(url, headers=HEADERS, timeout=10)

    if resp.status_code == 404:
        return None, None, "Subject not found."
    if resp.status_code != 200:
        return None, None, f"HTTP {resp.status_code}"

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

    name = ""
    h1 = soup.find("h1")
    if h1:
        name = h1.get_text(strip=True)

    drive_link = ""
    for a in soup.find_all("a", href=True):
        href = a["href"]
        if "drive.google.com/drive/folders" in href:
            drive_link = href.split("?")[0]
            break

    if not drive_link:
        return name, None, "No Google Drive link found on this page."

    return name, drive_link, None
