"""Повне оновлення місць розвантаження та їхніх цін з Excel, CSV або Google Таблиці.

Один рядок — одна ціна: місце + культура + клас. Місце, у якого кілька культур, повторюється в кількох
рядках; у наступних рядках назву й область можна залишити порожніми (як в об'єднаних клітинках Excel).
Місця, яких немає в таблиці, видаляються; ціни кожного місця стають такими, як у таблиці.
Місце впізнається за колонкою ID (з вивантаження) або за назвою та областю.

Також читається зведена таблиця закупівельних цін: культури в колонках, місця в рядках, області — рядки-підзаголовки.
У ній немає ID, тому місця, яких у таблиці немає, не видаляються, а лише показуються списком.
"""
import difflib
import re
from dataclasses import dataclass, field
from decimal import Decimal

from django.db import transaction

from farmerapp.models import CultureableName, District, Region
from .models import UnloadingPoint, UnloadingPointPrice
from .sheets import SheetImportError, number

# Ключ поля → початки назв колонок, за якими його впізнаємо (після нормалізації)
COLUMNS = {
    'id': ['id'],
    'name': ['назва', 'місце розвантаження', 'місце'],
    'terminal': ['термінал', 'покупець'],
    'region': ['область'],
    'district': ['район'],
    'settlement': ['населений пункт', 'нас пункт', 'населений'],
    'latitude': ['широта', 'lat'],
    'longitude': ['довгота', 'lng', 'lon'],
    'active': ['активне', 'активн'],
    'comment': ['коментар', 'примітка'],
    'culture': ['культура'],
    'specification': ['клас', 'специфікація'],
    'price': ['ціна'],
    'status': ['статус'],
}
REQUIRED = ['name', 'region', 'culture', 'price']
POINT_FIELDS = ['terminal', 'region', 'district', 'settlement', 'latitude', 'longitude', 'active', 'comment']
HEADERS = {
    'id': 'ID', 'name': 'Назва', 'terminal': 'Термінал / покупець', 'region': 'Область', 'district': 'Район',
    'settlement': 'Населений пункт', 'latitude': 'Широта', 'longitude': 'Довгота', 'active': 'Активне',
    'comment': 'Коментар', 'culture': 'Культура', 'specification': 'Клас / специфікація',
    'price': 'Ціна, грн з ПДВ/т', 'status': 'Статус',
}
STATUSES = {
    '': None, 'актуальна': 'active', 'активна': 'active', 'active': 'active',
    'оновлюється': 'updating', 'updating': 'updating', 'стоп': 'stop', 'stop': 'stop',
}
YES = {'', 'так', 'да', 'yes', 'true', '1', '+', 'активне'}
NO = {'ні', 'нет', 'no', 'false', '0', '-', 'неактивне'}

# Зведена таблиця
MATRIX_MIN_CULTURES = 3
# Культури без уточнення в колонках таблиці → запис довідника, де є лише озимі та ярі
MATRIX_DEFAULT_CULTURES = {'пшениця': 'пшениця озима', 'ячмінь': 'ячмінь озимий', 'ріпак': 'ріпак озимий'}
REGION_SUFFIXES = {'обл', 'область', 'лбл'}
# Підзаголовки, які не є областями. None — область визначається окремо для кожного місця
MATRIX_GROUPS = {'дунай': 'одеська', 'регіони': None, 'західні переходи': None}
# Місця, в назвах яких немає області
POINT_REGIONS = {'вадул': 'чернівецька', 'берегівське': 'закарпатська', 'пятидні': 'волинська', 'чоп': 'закарпатська'}
MATRIX_NO_VALUES = {'-', '–', '—'}


def _norm(value):
    return re.sub(r'\s+', ' ', re.sub(r'[^\w\s]', ' ', str(value or '').lower())).strip()


def _text(value):
    if value is None:
        return ''
    if isinstance(value, float) and value.is_integer():
        value = int(value)
    return str(value).strip()


def _place(value, suffixes):
    """«Вінницька обл.» → «вінницька», «Барський р-н» → «барський»."""
    words = [w for w in _norm(value).replace('р н', 'р-н').split() if w not in suffixes]
    return ' '.join(words)


def find_columns(rows):
    """Шукає рядок заголовків і повертає (номер рядка, {поле: індекс колонки})."""
    for index, row in enumerate(rows[:20]):
        columns = {}
        for position, cell in enumerate(row):
            header = _norm(cell)
            for key, prefixes in COLUMNS.items():
                if header and key not in columns and any(header.startswith(p) for p in prefixes):
                    columns[key] = position
                    break
        if all(key in columns for key in REQUIRED):
            return index, columns
    raise SheetImportError('Не знайдено рядок заголовків. Потрібні щонайменше колонки: '
                           + ', '.join(HEADERS[k] for k in REQUIRED) + '.')


@dataclass
class ParsedPoint:
    line: int
    name: str
    region: Region
    values: dict = field(default_factory=dict)
    prices: dict = field(default_factory=dict)   # (culture_id, клас у нижньому регістрі) → (культура, клас, ціна, статус)
    point_id: int = None
    existing: UnloadingPoint = None


@dataclass
class ImportPlan:
    points: list
    columns: set
    delete_missing: bool = True

    @property
    def price_count(self):
        return sum(len(p.prices) for p in self.points)


class _Lookup:
    def __init__(self):
        self.regions = {_place(r.name, {'область', 'обл'}): r for r in Region.objects.all()}
        self.districts = {}
        for district in District.objects.all():
            self.districts[(district.region_id, _place(district.name, {'район', 'р-н'}))] = district
        self.cultures = {c.cultureable_name.strip().lower(): c for c in CultureableName.objects.all()}


def parse_points(rows):
    try:
        header_index, columns = find_columns(rows)
    except SheetImportError:
        lookup = _Lookup()
        matrix = _find_matrix(rows, lookup)
        if matrix is None:
            raise
        return _parse_matrix(rows, matrix, lookup)
    lookup = _Lookup()
    errors, points, by_key, current = [], [], {}, None

    def cell(row, key):
        position = columns.get(key)
        return row[position] if position is not None and position < len(row) else None

    for line, row in enumerate(rows[header_index + 1:], start=header_index + 2):
        if not any(_text(c) for c in row):
            continue
        name, region_text = _text(cell(row, 'name')), _text(cell(row, 'region'))
        row_errors = []

        if name or region_text:
            region = lookup.regions.get(_place(region_text, {'область', 'обл'}))
            if not name:
                row_errors.append('не вказано назву місця')
            if region is None:
                row_errors.append(f'область «{region_text}» не знайдено' if region_text else 'не вказано область')
            if row_errors:
                errors.append(f'Рядок {line}: ' + '; '.join(row_errors) + '.')
                current = None
                continue
            key = (name.lower(), region.id)
            current = by_key.get(key)
            first_row = current is None
            if first_row:
                current = ParsedPoint(line=line, name=name, region=region)
                points.append(current)
                by_key[key] = current
            point_errors = _read_point_values(current, row, cell, columns, lookup, first_row)
            errors.extend(f'Рядок {line}: {e}' for e in point_errors)
        elif current is None:
            errors.append(f'Рядок {line}: не вказано назву місця й область.')
            continue

        culture_text = _text(cell(row, 'culture'))
        price_errors = _read_price(current, row, cell, culture_text, lookup) if culture_text else []
        if not culture_text and (_text(cell(row, 'price')) or _text(cell(row, 'specification'))):
            price_errors = ['вказано ціну без культури']
        errors.extend(f'Рядок {line}: {e}' for e in price_errors)

    if not points and not errors:
        errors.append('У таблиці немає жодного місця розвантаження.')
    if not errors:
        errors.extend(_match_existing(points, 'id' in columns))
    if errors:
        raise SheetImportError(errors)
    return ImportPlan(points=points, columns={k for k in columns if k in POINT_FIELDS})


def _read_point_values(point, row, cell, columns, lookup, first_row):
    errors, values = [], {}
    if 'id' in columns:
        raw = _text(cell(row, 'id'))
        if raw:
            if not raw.isdigit():
                errors.append(f'ID «{raw}» має бути числом.')
            elif point.point_id not in (None, int(raw)):
                errors.append(f'місце «{point.name}» має різні ID у різних рядках.')
            else:
                point.point_id = int(raw)
    for key in ('terminal', 'settlement', 'comment'):
        if key in columns:
            values[key] = _text(cell(row, key))
    if 'district' in columns:
        district_text = _text(cell(row, 'district'))
        district = lookup.districts.get((point.region.id, _place(district_text, {'район', 'р-н'})))
        if district_text and district is None:
            errors.append(f'район «{district_text}» не знайдено в області {point.region.name}.')
        values['district'] = district
    for key in ('latitude', 'longitude'):
        if key in columns:
            raw = cell(row, key)
            value = number(raw)
            if _text(raw) and value is None:
                errors.append(f'{HEADERS[key].lower()} «{_text(raw)}» має бути числом.')
            values[key] = value.quantize(Decimal('0.000001')) if value is not None else None
    if 'latitude' in values and 'longitude' in values and (values['latitude'] is None) != (values['longitude'] is None):
        errors.append('вкажіть і широту, і довготу, або залиште обидві порожніми.')
    if 'active' in columns:
        raw = _norm(cell(row, 'active'))
        if raw not in YES | NO:
            errors.append(f'«Активне» має бути «так» або «ні», а не «{_text(cell(row, "active"))}».')
        if raw or first_row:
            values['active'] = raw not in NO

    if not first_row:
        # Повторний рядок того ж місця: заповнені поля мають збігатися з першим рядком
        for key, value in values.items():
            if value not in ('', None) and point.values.get(key) not in ('', None, value):
                errors.append(f'для місця «{point.name}» поле «{HEADERS[key]}» відрізняється від рядка {point.line}.')
        for key, value in values.items():
            if point.values.get(key) in ('', None):
                point.values[key] = value
    else:
        point.values = values
    return errors


def _read_price(point, row, cell, culture_text, lookup):
    culture = lookup.cultures.get(culture_text.lower())
    if culture is None:
        return [f'культуру «{culture_text}» не знайдено в довіднику.']
    specification = _text(cell(row, 'specification'))
    raw_price, raw_status = cell(row, 'price'), _norm(cell(row, 'status'))
    price = number(raw_price)
    if _text(raw_price) and price is None:
        return [f'ціна «{_text(raw_price)}» має бути числом.']
    if price is not None and (price <= 0 or price >= 10 ** 10):
        return [f'ціна {price} поза допустимими межами.']
    if raw_status not in STATUSES:
        return [f'статус «{_text(cell(row, "status"))}» — має бути «Актуальна», «Оновлюється» або «Стоп».']
    status = STATUSES[raw_status] or ('active' if price is not None else 'updating')
    if status == 'active' and price is None:
        return ['для статусу «Актуальна» потрібна ціна.']
    key = (culture.id, specification.lower())
    if key in point.prices:
        spec = f' {specification}' if specification else ''
        return [f'{culture}{spec} для місця «{point.name}» вказано двічі.']
    point.prices[key] = (culture, specification, price.quantize(Decimal('0.01')) if price is not None else None, status)
    return []


@dataclass
class _Matrix:
    header_index: int
    name_column: int
    terminal_column: int
    prices: dict    # номер колонки → (культура, клас, заголовок)
    errors: list


def _matrix_culture(header, lookup):
    """«Пшениця 2 клас» → (Пшениця озима, «2 клас»); None, якщо культуру не впізнано."""
    text = ' '.join(_text(header).split())
    lower = text.lower()
    for name in sorted(lookup.cultures, key=len, reverse=True):
        if lower == name or lower.startswith(name + ' '):
            return lookup.cultures[name], text[len(name):].strip()
    first_word = lower.split(' ')[0]
    culture = lookup.cultures.get(MATRIX_DEFAULT_CULTURES.get(first_word))
    return (culture, text[len(first_word):].strip()) if culture else None


def _find_matrix(rows, lookup):
    """Шукає рядок із культурами в колонках; None, якщо таблиця не зведена."""
    for index, row in enumerate(rows[:20]):
        headers = {position: cell for position, cell in enumerate(row) if _text(cell)}
        cultures = {position: _matrix_culture(cell, lookup) for position, cell in headers.items()}
        found = [position for position, culture in cultures.items() if culture]
        if len(found) < MATRIX_MIN_CULTURES or found[0] == 0:
            continue
        matrix = _Matrix(index, found[0] - 1, None, {}, [])
        seen = set()
        for position, header in headers.items():
            title = ' '.join(_text(header).split())
            if position <= matrix.name_column:
                continue
            if any(_norm(header).startswith(p) for p in COLUMNS['terminal']):
                matrix.terminal_column = position
            elif cultures[position] is None:
                matrix.errors.append(f'Колонка «{title}»: культуру не знайдено в довіднику.')
            else:
                culture, specification = cultures[position]
                key = (culture.id, specification.lower())
                if key in seen:
                    matrix.errors.append(f'Колонка «{title}» повторюється.')
                seen.add(key)
                matrix.prices[position] = (culture, specification, title)
        return matrix
    return None


def _matrix_heading(name, lookup):
    """Повертає (чи це підзаголовок, область підзаголовка)."""
    words = _norm(name).split()
    text = ' '.join(words)
    if text in MATRIX_GROUPS:
        return True, lookup.regions.get(MATRIX_GROUPS[text])
    if words[-1] not in REGION_SUFFIXES and text not in lookup.regions:
        return False, None
    # Назви областей у таблиці пишуть із помилками: «Киівська», «Дпіпропетроська»
    place = ' '.join(w for w in words if w not in REGION_SUFFIXES)
    match = difflib.get_close_matches(place, lookup.regions, n=1, cutoff=0.82)
    return (True, lookup.regions[match[0]]) if match else (False, None)


def _region_from_name(name, lookup):
    text = _norm(name)
    for prefix, region in POINT_REGIONS.items():
        if text.startswith(prefix):
            return lookup.regions.get(region)
    return next((region for key, region in lookup.regions.items() if key in text), None)


def _matrix_price(raw):
    """Значення клітинки → (ціна, статус, помилка). (None, None, None) — ціни немає."""
    text = _text(raw)
    if text in MATRIX_NO_VALUES:
        return None, None, None
    normalized = _norm(text)
    if normalized.startswith(('оновл', 'новл')):
        return None, 'updating', None
    if normalized in ('стоп', 'stop'):
        return None, 'stop', None
    price = number(raw)
    if price is None:
        return None, None, f'«{text}» — має бути ціна, «оновл», «стоп» або «-».'
    if price <= 0 or price >= 10 ** 10:
        return None, None, f'ціна {price} поза допустимими межами.'
    return price.quantize(Decimal('0.01')), 'active', None


def _parse_matrix(rows, matrix, lookup):
    errors, points, by_key, region = list(matrix.errors), [], {}, None
    terminal_column = matrix.terminal_column

    for line, row in enumerate(rows[matrix.header_index + 1:], start=matrix.header_index + 2):
        cell = lambda position: _text(row[position]) if position is not None and position < len(row) else ''
        name = ' '.join(cell(matrix.name_column).split()).rstrip(' ,:;')
        filled = [position for position in matrix.prices if cell(position)]
        terminal = cell(terminal_column)
        if not name:
            if filled or terminal:
                errors.append(f'Рядок {line}: вказано ціни без назви місця.')
            continue
        if not filled and not terminal:
            is_heading, heading_region = _matrix_heading(name, lookup)
            if is_heading:
                region = heading_region
                continue

        point_region = region or _region_from_name(name, lookup)
        if point_region is None:
            errors.append(f'Рядок {line}: для місця «{name}» не вдалося визначити область. '
                          'Додайте її до назви, наприклад «Ягодин, Волинська обл».')
            continue
        key = (_point_key(name), point_region.id)
        if key in by_key:
            errors.append(f'Рядки {by_key[key].line} і {line}: місце «{name}» вказано двічі.')
            continue
        point = ParsedPoint(line=line, name=name, region=point_region)
        if terminal:
            point.values['terminal'] = terminal
        by_key[key] = point
        points.append(point)

        for position in filled:
            culture, specification, title = matrix.prices[position]
            price, status, error = _matrix_price(row[position])
            if error:
                errors.append(f'Рядок {line}, колонка «{title}»: {error}')
            elif status:
                point.prices[(culture.id, specification.lower())] = (culture, specification, price, status)

    if not points and not errors:
        errors.append('У таблиці немає жодного місця розвантаження.')
    if not errors:
        errors.extend(_match_existing(points, False))
    if errors:
        raise SheetImportError(errors)
    return ImportPlan(points=points, columns={'terminal'} if terminal_column is not None else set(), delete_missing=False)


def _point_key(name):
    return ' '.join(name.lower().split()).rstrip(' ,:;')


def _match_existing(points, has_ids):
    errors = []
    existing = {p.id: p for p in UnloadingPoint.objects.all()}
    by_name = {(_point_key(p.name), p.region_id): p for p in existing.values()}
    used = {}
    for point in points:
        if point.point_id is not None:
            point.existing = existing.get(point.point_id)
            if point.existing is None:
                errors.append(f'Рядок {point.line}: місця з ID {point.point_id} немає. Залиште ID порожнім для нового місця.')
                continue
        else:
            point.existing = by_name.get((_point_key(point.name), point.region.id))
        if point.existing is not None:
            if point.existing.id in used:
                errors.append(f'Рядки {used[point.existing.id]} і {point.line} стосуються одного й того ж місця.')
            used[point.existing.id] = point.line
    return errors


@dataclass
class ImportResult:
    created: int = 0
    updated: int = 0
    unchanged: int = 0
    deleted: int = 0
    deleted_names: list = field(default_factory=list)
    missing_names: list = field(default_factory=list)   # немає в таблиці, але не видалені


@transaction.atomic
def apply_plan(plan):
    result = ImportResult()
    kept_ids = set()
    for parsed in plan.points:
        point = parsed.existing or UnloadingPoint()
        changed = point.pk is None
        updates = {'name': parsed.name, 'region': parsed.region}
        updates.update({k: v for k, v in parsed.values.items() if k in plan.columns})
        for key, value in updates.items():
            if changed or getattr(point, key) != value:
                setattr(point, key, value)
                changed = True
        if point.pk is None:
            point.save()
        changed = _sync_prices(point, parsed.prices) or changed
        if changed:
            point.save()
            if parsed.existing is None:
                result.created += 1
            else:
                result.updated += 1
        else:
            result.unchanged += 1
        kept_ids.add(point.id)

    stale = UnloadingPoint.objects.exclude(id__in=kept_ids)
    names = list(stale.values_list('name', flat=True))
    if not plan.delete_missing:
        result.missing_names = names
        return result
    result.deleted_names = names
    result.deleted = len(names)
    stale.delete()
    return result


def _sync_prices(point, prices):
    changed = False
    current = {(p.culture_id, p.specification.strip().lower()): p for p in point.prices.all()}
    for key, (culture, specification, price, status) in prices.items():
        existing = current.pop(key, None)
        if existing is None:
            UnloadingPointPrice.objects.create(unloading_point=point, culture=culture, specification=specification,
                                               price=price, status=status)
            changed = True
        elif (existing.price, existing.status, existing.specification) != (price, status, specification):
            existing.price, existing.status, existing.specification = price, status, specification
            existing.save()
            changed = True
    if current:
        UnloadingPointPrice.objects.filter(id__in=[p.id for p in current.values()]).delete()
        changed = True
    return changed


def export_rows():
    """Поточні місця і ціни у форматі, який приймає імпорт."""
    keys = list(HEADERS)
    yield [HEADERS[k] for k in keys]
    statuses = dict(UnloadingPointPrice.STATUS_CHOICES)
    points = UnloadingPoint.objects.select_related('region', 'district').prefetch_related('prices__culture')
    for point in points.order_by('region__name', 'name'):
        base = {
            'id': point.id, 'name': point.name, 'terminal': point.terminal, 'region': point.region.name,
            'district': point.district.name if point.district else '', 'settlement': point.settlement,
            'latitude': point.latitude, 'longitude': point.longitude, 'active': 'так' if point.active else 'ні',
            'comment': point.comment,
        }
        prices = list(point.prices.all()) or [None]
        for price in prices:
            row = dict(base)
            if price is not None:
                row.update(culture=price.culture.cultureable_name, specification=price.specification,
                           price=price.price, status=statuses[price.status])
            yield [row.get(k, '') if row.get(k) is not None else '' for k in keys]
