"""Google Sheets API service wrapper."""

from __future__ import annotations

from typing import Any, Optional

from googleapiclient.discovery import build

from ..auth.oauth import get_credentials, resolve_profile


def _get_service(profile: Optional[str] = None):
    return build("sheets", "v4", credentials=get_credentials(resolve_profile(profile)))


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def read(
    spreadsheet_id: str,
    range: str,
    profile: Optional[str] = None,
) -> dict[str, Any]:
    svc = _get_service(profile)
    res = svc.spreadsheets().values().get(
        spreadsheetId=spreadsheet_id, range=range,
    ).execute()
    return {
        "range": res.get("range"),
        "values": res.get("values", []),
        "rowCount": len(res.get("values", [])),
    }


def write(
    spreadsheet_id: str,
    range: str,
    values: list[list[Any]],
    profile: Optional[str] = None,
) -> dict[str, Any]:
    svc = _get_service(profile)
    res = svc.spreadsheets().values().update(
        spreadsheetId=spreadsheet_id,
        range=range,
        valueInputOption="USER_ENTERED",
        body={"values": values},
    ).execute()
    return {
        "updatedRange": res.get("updatedRange"),
        "updatedRows": res.get("updatedRows"),
        "updatedColumns": res.get("updatedColumns"),
        "updatedCells": res.get("updatedCells"),
    }


def append(
    spreadsheet_id: str,
    range: str,
    values: list[list[Any]],
    profile: Optional[str] = None,
) -> dict[str, Any]:
    svc = _get_service(profile)
    res = svc.spreadsheets().values().append(
        spreadsheetId=spreadsheet_id,
        range=range,
        valueInputOption="USER_ENTERED",
        insertDataOption="INSERT_ROWS",
        body={"values": values},
    ).execute()
    updates = res.get("updates", {})
    return {
        "updatedRange": updates.get("updatedRange"),
        "updatedRows": updates.get("updatedRows"),
        "updatedCells": updates.get("updatedCells"),
    }


def create(
    title: str,
    sheet_names: Optional[list[str]] = None,
    profile: Optional[str] = None,
) -> dict[str, Any]:
    svc = _get_service(profile)
    names = sheet_names or ["Sheet1"]
    res = svc.spreadsheets().create(body={
        "properties": {"title": title},
        "sheets": [{"properties": {"title": n}} for n in names],
    }).execute()
    return {
        "spreadsheetId": res["spreadsheetId"],
        "spreadsheetUrl": res.get("spreadsheetUrl"),
        "title": res["properties"]["title"],
        "sheets": [s["properties"]["title"] for s in res.get("sheets", [])],
    }


def info(spreadsheet_id: str, profile: Optional[str] = None) -> dict[str, Any]:
    svc = _get_service(profile)
    res = svc.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
    return {
        "spreadsheetId": res["spreadsheetId"],
        "title": res["properties"]["title"],
        "locale": res["properties"].get("locale"),
        "spreadsheetUrl": res.get("spreadsheetUrl"),
        "sheets": [
            {
                "title": s["properties"]["title"],
                "sheetId": s["properties"]["sheetId"],
                "rowCount": s["properties"].get("gridProperties", {}).get("rowCount"),
                "columnCount": s["properties"].get("gridProperties", {}).get("columnCount"),
            }
            for s in res.get("sheets", [])
        ],
    }
