"""Upload master inventory CSV to Google Sheets (optional integration)."""

import csv
import os
from pathlib import Path
from typing import List, Optional


SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
DEFAULT_CHUNK_SIZE = 500


def _read_csv_rows(path: str) -> List[List[str]]:
    rows: List[List[str]] = []
    with open(path, newline="", encoding="utf-8") as handle:
        reader = csv.reader(handle)
        for row in reader:
            rows.append([str(cell) for cell in row])
    return rows


def run_if_configured(csv_path: str, worksheet: str = "Sheet1") -> str:
    """Upload CSV to Google Sheets if credentials are configured.

    Requires environment variables:
      GOOGLE_SHEETS_CREDENTIALS - path to service account JSON
      GOOGLE_SHEETS_SHEET_ID - the spreadsheet ID
    """
    credentials_path = os.environ.get("GOOGLE_SHEETS_CREDENTIALS", "")
    sheet_id = os.environ.get("GOOGLE_SHEETS_SHEET_ID", "")
    worksheet = os.environ.get("GOOGLE_SHEETS_WORKSHEET", worksheet)

    if not credentials_path or not sheet_id:
        return "Google Sheets not configured. Skipping upload. Set GOOGLE_SHEETS_CREDENTIALS and GOOGLE_SHEETS_SHEET_ID."

    if not os.path.exists(credentials_path):
        return f"Google Sheets credentials file not found: {credentials_path}. Skipping upload."

    if not os.path.exists(csv_path):
        return f"CSV file not found: {csv_path}. Skipping upload."

    try:
        from google.oauth2.service_account import Credentials
        from googleapiclient.discovery import build
    except ImportError:
        return "Google Sheets libraries not installed. Run: pip install mentorr[sheets]"

    try:
        creds = Credentials.from_service_account_file(credentials_path, scopes=SCOPES)
        service = build("sheets", "v4", credentials=creds)

        rows = _read_csv_rows(csv_path)

        # Clear and upload
        service.spreadsheets().values().clear(
            spreadsheetId=sheet_id, range=worksheet, body={}
        ).execute()

        if not rows:
            return "No rows to upload."

        for i in range(0, len(rows), DEFAULT_CHUNK_SIZE):
            chunk = rows[i:i + DEFAULT_CHUNK_SIZE]
            service.spreadsheets().values().update(
                spreadsheetId=sheet_id,
                range=f"{worksheet}!A{i + 1}",
                valueInputOption="RAW",
                body={"values": chunk},
            ).execute()

        return f"Uploaded {len(rows)} rows to Google Sheet ({worksheet})."

    except Exception as e:
        return f"Google Sheets upload failed: {e}"
