"""Читання таблиць для імпорту: Excel, CSV і Google Таблиці (за посиланням з доступом на читання)."""
import csv
import io
import re
from decimal import Decimal, InvalidOperation

import openpyxl
import requests

GOOGLE_SHEET_RE = re.compile(r'docs\.google\.com/spreadsheets/d/([A-Za-z0-9_-]+)')
GOOGLE_GID_RE = re.compile(r'[#&?]gid=(\d+)')


class SheetImportError(Exception):
    def __init__(self, errors):
        self.errors = errors if isinstance(errors, list) else [errors]
        super().__init__('; '.join(self.errors))


def number(value):
    if value is None:
        return None
    if isinstance(value, (int, float, Decimal)):
        return Decimal(str(value))
    text = str(value).strip().replace('\xa0', '').replace(' ', '').replace(',', '.')
    if not text:
        return None
    try:
        result = Decimal(text)
    except InvalidOperation:
        return None
    return result if result.is_finite() else None


def read_upload(upload):
    name = upload.name.lower()
    if name.endswith(('.xlsx', '.xlsm')):
        try:
            sheet = openpyxl.load_workbook(upload, read_only=True, data_only=True).worksheets[0]
        except Exception:
            raise SheetImportError('Не вдалося прочитати файл Excel. Збережіть його у форматі .xlsx.')
        return [list(row) for row in sheet.iter_rows(values_only=True)]
    if name.endswith('.csv'):
        return read_csv(upload.read())
    raise SheetImportError('Підтримуються файли .xlsx і .csv.')


def read_csv(content):
    text = content.decode('utf-8-sig', errors='replace') if isinstance(content, bytes) else content
    try:
        dialect = csv.Sniffer().sniff(text[:2000], delimiters=',;\t')
    except csv.Error:
        dialect = csv.excel
    return list(csv.reader(io.StringIO(text), dialect))


def google_export_url(url):
    match = GOOGLE_SHEET_RE.search(url or '')
    if not match:
        raise SheetImportError('Це не схоже на посилання на Google Таблицю (docs.google.com/spreadsheets/…).')
    gid = GOOGLE_GID_RE.search(url)
    export = f'https://docs.google.com/spreadsheets/d/{match.group(1)}/export?format=csv'
    return export + (f'&gid={gid.group(1)}' if gid else '')


def read_google_sheet(url):
    try:
        response = requests.get(google_export_url(url), timeout=20)
    except requests.RequestException:
        raise SheetImportError('Не вдалося з\'єднатися з Google Таблицями. Спробуйте ще раз.')
    if response.status_code != 200 or 'text/csv' not in response.headers.get('Content-Type', ''):
        raise SheetImportError('Google не віддав таблицю. Відкрийте доступ «Усі, хто має посилання — читач» '
                                'і перевірте посилання.')
    return read_csv(response.content)
