import gspread
from io import StringIO
import csv
import os
import sys

# Configuration de l'API Google Sheets
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
script_directory = os.path.dirname(os.path.abspath(__file__))
credentials_path = os.path.join(script_directory, 'credentials.json')

def save_to_file(sheet_url, local_path):
    # Extract the Google Sheet ID from the URL
    SPREADSHEET_ID = sheet_url.split('/')[-2]

    gc = gspread.service_account(filename=credentials_path)
    sh = gc.open_by_key(SPREADSHEET_ID)

    worksheet = sh.get_worksheet(0)  # Get the first worksheet
    data = worksheet.get_all_values()

    # Convert data to CSV format
    csv_io = StringIO()
    csv_writer = csv.writer(csv_io)
    csv_writer.writerows(data)

    if local_path.endswith(".csv"):
        with open(local_path, 'w', newline='') as f:
            f.write(csv_io.getvalue())
    else:
        with open(os.path.join(local_path, 'stock.csv'), 'w', newline='') as f:
            f.write(csv_io.getvalue())

    print("Data saved successfully to the local file.")

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print("Usage: python3 script_name.py <google_sheet_url> <local_path>")
    else:
        save_to_file(sys.argv[1], sys.argv[2])