﻿#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import re
import urllib.parse
import json
import sys
import datetime

def do_c(a):
    a = re.sub(r'[^\d\.,]', '', str(a))
    a = a.replace(',', '.')
    try:
        return float(a)
    except:
        return 0.0

def has_ukrainian_phone(text):
    """
    Проверка наличия украинских телефонных номеров
    """
    text_lower = text.lower()
    
    # Убираем плюс в начале для унификации
    text_clean = re.sub(r'^\+', '', text_lower)
    
    # Вариант 1: 12 цифр подряд (без разделителей)
    if re.search(r'380\d{9}', text_clean):
        return True
    
    # Вариант 2: С разделителями (пробел, дефис, тире, скобки)
    allowed_separators = r'[\s\-\(\)]*'
    pattern = r'380' + allowed_separators + \
              r'\d' + allowed_separators + \
              r'\d' + allowed_separators + \
              r'\d' + allowed_separators + \
              r'\d' + allowed_separators + \
              r'\d' + allowed_separators + \
              r'\d' + allowed_separators + \
              r'\d' + allowed_separators + \
              r'\d' + allowed_separators + \
              r'\d'
    
    if re.search(pattern, text_clean):
        return True
    
    return False

def extract_year(text):
    """
    Извлечение года из текста с поддержкой укороченных форматов
    Примеры:
    - 2024 -> 2024
    - 24 -> 2024
    - 98 -> 1998
    - 6 год -> 2006
    """
    text_lower = text.lower()
    text_lower = text_lower.replace('г.', 'г')
    
    current_year = datetime.datetime.now().year
    current_century = (current_year // 100) * 100  # 2000
    current_two_digit = current_year % 100  # 24 для 2024
    
    def normalize_short_year(short_year):
        """Нормализация двузначного года на основе текущего года"""
        if short_year <= current_two_digit:
            return current_century + short_year
        else:
            return (current_century - 100) + short_year
    
    # 1. Полный год (2024, 1998)
    match = re.search(r'\b(19[0-9]{2}|20[0-9]{2})\s*г(?:од(?:а)?)?', text_lower)
    if match:
        return int(match.group(1))
    
    # 2. Полный год без слова "год"
    match = re.search(r'\b(19[0-9]{2}|20[0-9]{2})\b', text_lower)
    if match:
        return int(match.group(1))
    
    # 3. Двузначный год с "г" или "год" (24 г, 98 год)
    match = re.search(r'\b(\d{2})\s*г(?:од(?:а)?)?', text_lower)
    if match:
        return normalize_short_year(int(match.group(1)))
    
    # 4. Однозначный год с "г" или "год" (6 год)
    match = re.search(r'\b(\d)\s*г(?:од(?:а)?)?', text_lower)
    if match:
        return current_century + int(match.group(1))
    
    return None

def extract_price_simple(text):
    # Если есть украинский номер, не парсим цену
    if has_ukrainian_phone(text):
        return None
    
    text_lower = text.lower()
    
    # Нормализация искажённых букв
    replacements = {
        'e': 'е', 'p': 'р', 'y': 'у', 'o': 'о', 'a': 'а',
        'c': 'с', 'x': 'х', 'k': 'к', 'm': 'м', 't': 'т',
        'p.': 'р.', 'pуб': 'руб', 'цeнa': 'цена'
    }
    for wrong, correct in replacements.items():
        text_lower = text_lower.replace(wrong, correct)
    
    text_lower = text_lower.replace('₽', ' руб')
    text_lower = re.sub(r'\bторг\b', ',', text_lower)
    
    # Нормализация чисел
    text_lower = re.sub(r'(\d+)\s+(\d{3})', r'\1\2', text_lower)
    text_lower = re.sub(r'(\d+)\.(\d{3})\.(\d{3})', r'\1\2\3', text_lower)
    text_lower = re.sub(r'(\d+)\.(\d{3})', r'\1\2', text_lower)
    
    # 1. Составная цена
    match = re.search(r'(\d+(?:\.\d+)?)\s*(?:млн|миллиона?)\s*(?:(\d+)\s*тыс)?', text_lower)
    if match:
        millions = float(match.group(1))
        thousands = int(match.group(2)) if match.group(2) else 0
        return int(millions * 1_000_000 + thousands * 1000)
    
    # 2. Цена с "т.р." (160т.р., 160 т.р.)
    match = re.search(r'(\d+)\s*т\.?\s*р\.?(?=\s|$|[^\w])', text_lower)
    if match:
        return int(match.group(1)) * 1000
    
    # 3. Цена после слова "цена" с "т"
    match = re.search(r'цена\s*(\d+)\s*т(?:ыс(?:яч)?)?\.?\s*(?:р\.?|руб)?', text_lower)
    if match:
        return int(match.group(1)) * 1000
    
    # 4. Цена после слова "цена"
    match = re.search(r'цена\s*:?\s*(\d[\d\s\.]*\d)', text_lower)
    if match:
        num_str = match.group(1).replace(' ', '').replace('.', '')
        return int(num_str)
    
    # 5. Цена с "тыс руб"
    match = re.search(r'(\d+)\s*тыс\s*(?:руб|р\.?)(?=\s|$|[^\w])', text_lower)
    if match:
        return int(match.group(1)) * 1000
    
    # 6. Цена с пробелами и "р." - буква "р" должна быть отдельным словом или сокращением
    # Ищем: число, затем пробел, затем "р" или "р." и после этого не буква (или конец строки)
    match = re.search(r'(\d[\d\s\.]*\d)\s+р\.?(?=\s|$|[^\wа-яё])', text_lower)
    if match:
        num_str = match.group(1).replace(' ', '').replace('.', '')
        return int(num_str)
    
    # 7. Обычное число с "р." или "руб" - "р" должно быть отдельным словом
    # Важно: "р" не должна быть частью слова (как в "регион", "размер")
    match = re.search(r'(\d+)\s+(?:руб|р\.?(?=\s|$|[^\wа-яё]))', text_lower)
    if match:
        return int(match.group(1))
    
    # 8. Число с "р" без пробела (500р) - только если после "р" ничего нет или конец строки
    match = re.search(r'(\d+)р(?!\w)', text_lower)
    if match:
        return int(match.group(1))
    
    # 9. Число с одной точкой
    match = re.search(r'\b(\d{1,3}\.\d{3})\b', text_lower)
    if match:
        num_str = match.group(1).replace('.', '')
        return int(num_str)
    
    return None

def extract_mileage_simple(text):
    text_lower = text.lower()
    
    replacements = {'e': 'е', 'o': 'о', 'p': 'р'}
    for wrong, correct in replacements.items():
        text_lower = text_lower.replace(wrong, correct)
    
    text_lower = re.sub(r'(\d+)\s+(\d{3})', r'\1\2', text_lower)
    text_lower = re.sub(r'(\d+)\.(\d{3})', r'\1\2', text_lower)
    
    # 1. пробег 176тыс.км
    match = re.search(r'пробег\s*[:\-]?\s*(\d+)\s*тыс\.?\s*км', text_lower)
    if match:
        return int(match.group(1)) * 1000
    
    # 2. пробег 176 тыс км
    match = re.search(r'пробег\s*[:\-]?\s*(\d+)\s*тыс\s*км', text_lower)
    if match:
        return int(match.group(1)) * 1000
    
    # 3. пробег 176000 км
    match = re.search(r'пробег\s*[:\-]?\s*(\d+)\s*км', text_lower)
    if match:
        return int(match.group(1))
    
    # 4. 176000 км
    match = re.search(r'(\d+)\s*км', text_lower)
    if match:
        return int(match.group(1))
    
    # 5. пробег 176 тыс
    match = re.search(r'пробег\s*[:\-]?\s*(\d+)\s*тыс', text_lower)
    if match:
        return int(match.group(1)) * 1000
    
    # 6. пробег 176000
    match = re.search(r'пробег\s*[:\-]?\s*(\d+)', text_lower)
    if match:
        return int(match.group(1))
    
    # 7. число перед "пробег"
    match = re.search(r'(\d+)\s+пробег', text_lower)
    if match:
        return int(match.group(1))
    
    # 8. 176 тыс
    match = re.search(r'(\d+)\s*тыс', text_lower)
    if match:
        val = int(match.group(1))
        start_pos = max(0, match.start() - 30)
        context = text_lower[start_pos:match.end()]
        if 'цена' not in context and 'руб' not in context:
            if val < 1000:
                return val * 1000
            return val
    
    return None

def is_car_sale(text, required_params):
    # Проверка на украинский номер
    if has_ukrainian_phone(text):
        return False, {
            'price': None,
            'mileage': None,
            'year': None,
            'banned': True
        }, ['Украинский номер телефона']
    
    price = extract_price_simple(text)
    mileage = extract_mileage_simple(text)
    year = extract_year(text)  # Используем новую функцию
    
    has_price = price is not None
    has_mileage = mileage is not None
    has_year = year is not None
    
    markers = {
        'price': price,
        'mileage': mileage,
        'year': year,
        'banned': False
    }
    
    if required_params:
        missing = []
        if 'price' in required_params and not has_price:
            missing.append('цена')
        if 'mileage' in required_params and not has_mileage:
            missing.append('пробег')
        if 'year' in required_params and not has_year:
            missing.append('год')
        
        if missing:
            return False, markers, missing
        else:
            return True, markers, []
    
    sale_words = ['продам', 'продажа', 'продаю', 'продаётся', 'срочно']
    car_words = ['авто', 'автомобиль', 'машина']
    
    has_sale_word = any(w in text_lower for w in sale_words)
    has_car_word = any(w in text_lower for w in car_words)
    
    if has_sale_word and has_car_word:
        return True, markers, []
    if has_price:
        return True, markers, []
    
    return False, markers, []

# ===== CGI =====
query_string = os.environ.get('QUERY_STRING', '')
params = urllib.parse.parse_qs(query_string)

user_text = params.get('user_text', [''])[0]
required_str = params.get('required', [''])[0]
required_params = required_str.split(',') if required_str else []

# Формируем ответ
response = {
    'success': False,
    'is_sale': False,
    'price': None,
    'mileage': None,
    'year': None,
    'missing': [],
    'banned': False,
    'banned_reason': None,
    'error': None
}

if not user_text:
    response['error'] = 'Текст не получен'
else:
    is_sale, markers, missing = is_car_sale(user_text, required_params)
    
    response['success'] = True
    response['is_sale'] = is_sale
    response['price'] = markers['price']
    response['mileage'] = markers['mileage']
    response['year'] = markers['year']
    response['missing'] = missing
    response['banned'] = markers.get('banned', False)
    if markers.get('banned'):
        response['banned_reason'] = 'ukrainian_phone'

# Выводим JSON
print(json.dumps(response, ensure_ascii=False, indent=2))