from __future__ import annotations

import re
from urllib.parse import quote

from google.auth.transport.requests import AuthorizedSession

from worai.core.google_oauth import SHEETS_SCOPES, load_google_credentials
from worai.errors import UsageError


_SPREADSHEET_ID_PATTERN = re.compile(r"/spreadsheets/d/([a-zA-Z0-9-_]+)")


def extract_spreadsheet_id(value: str) -> str | None:
    match = _SPREADSHEET_ID_PATTERN.search(value)
    if match:
        return match.group(1)
    if re.fullmatch(r"[a-zA-Z0-9-_]{20,}", value):
        return value
    return None


def is_spreadsheet_source(value: str) -> bool:
    return extract_spreadsheet_id(value) is not None


def load_urls_from_sheet(
    source: str,
    sheet_name: str,
    *,
    client_secrets: str | None,
    token: str,
    port: int,
) -> list[str]:
    spreadsheet_id = extract_spreadsheet_id(source)
    if not spreadsheet_id:
        raise UsageError("Invalid Google Sheets source. Provide a spreadsheet URL or ID.")

    creds = load_google_credentials(
        client_secrets_path=client_secrets,
        token_path=token,
        port=port,
        scopes=SHEETS_SCOPES,
    )
    session = AuthorizedSession(creds)
    encoded_range = quote(f"'{sheet_name}'", safe="")
    url = f"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}/values/{encoded_range}"
    response = session.get(url)
    if response.status_code != 200:
        raise RuntimeError(
            f"Failed to read source spreadsheet values ({response.status_code}): {response.text}"
        )

    values = (response.json() or {}).get("values") or []
    if not values:
        return []
    headers = [str(v).strip().lower() for v in values[0]]
    if "url" not in headers:
        raise UsageError(f"Source sheet '{sheet_name}' is missing required 'url' column.")
    idx = headers.index("url")

    urls: list[str] = []
    for row in values[1:]:
        if idx < len(row):
            cell = str(row[idx]).strip()
            if cell:
                urls.append(cell)
    return urls
