from flask import request, jsonify, session
from InvestmentManager import investmentmanager_bp
from modules.core.offer_queries import list_active_offers
from modules.core import storage_paths
from modules.core.json_store import locked_json, read_json, write_json_atomic
import os
import json
from datetime import datetime
import unicodedata

# Ścieżka do pliku z leadami -- resolved on every call (not at import) so
# DATA_DIR from .env is honoured; the file is created on first save.
def _leads_path():
    return str(storage_paths.knowledge_center_manual_leads_path())

# -------------------------------
# Pomocnicze
# -------------------------------
def load_leads():
    """Current leads ([] when the file does not exist yet). A damaged file raises JsonStoreCorrupt (HTTP 503 via the blueprint
    error handler) - it is never presented as an empty list."""
    return read_json(_leads_path(), list)

def save_leads(leads):
    """Atomic replacement of the whole list. Routes must change leads through `_leads_transaction()` instead."""
    write_json_atomic(_leads_path(), leads)

def _leads_transaction():
    """One read-modify-write of the shared leads file under an inter-process lock (see modules/core/json_store.py)."""
    return locked_json(_leads_path(), list)

def get_estates_for_leads(limit=100):
    """
    Zwraca aktywne oferty jako listę słowników, gotowych do dopasowania z leadami.
    Wypisuje dane do konsoli dla debugowania.
    """
    estates = list_active_offers(limit)

    return estates

# -------------------------------
# Endpoint: Dodanie klienta poszukującego (lead ręczny)
# -------------------------------
@investmentmanager_bp.route('/leadhunter/add_manual_lead', methods=['POST'])
def add_manual_lead():
    data = request.get_json()

    name = data.get('name', '').strip()
    phone = data.get('phone', '').strip()

    if not name or not phone:
        return jsonify({'error': 'Imię i telefon są wymagane.'}), 400

    # Przygotuj bazową strukturę leada
    new_lead = {
        "id": datetime.now().strftime('%Y%m%d%H%M%S%f'),
        "created_by": session['user_id'],
        "created_name": session.get('first_name', '') + " " + session.get('last_name', ''),
        "name": name,
        "phone": phone,
        "status": "nowy",
        "timestamp": datetime.now().isoformat()
    }

    # Dodaj dodatkowe klucze dynamicznie (z wyjątkiem pól już użytych powyżej)
    skip_keys = {'id', 'created_by', 'created_name', 'type', 'name', 'phone', 'status', 'timestamp'}
    for key, value in data.items():
        if key not in skip_keys:
            # Obsłuż przypadek gdy frontend wysyła np. pojedynczy string, ale backend spodziewa się listy
            if key in ['typ_oferty', 'typ_nieruchomosci'] and isinstance(value, str):
                value = [value]
            new_lead[key] = value

    with _leads_transaction() as leads:
        leads.insert(0, new_lead)

    # Zapisz dopasowania do pliku
    estates = get_estates_for_leads(limit=100)
    matched_estates = match_estates_to_lead(new_lead, estates)

    return jsonify({'message': 'Lead zapisany pomyślnie'}), 200

# -------------------------------
# Endpoint: Edycja leadu
# -------------------------------
@investmentmanager_bp.route('/leadhunter/update_lead', methods=['POST'])
def update_lead():
    data = request.get_json()
    lead_id = data.get('id')
    if not lead_id:
        return jsonify({'error': 'Brak ID leada'}), 400

    with _leads_transaction() as leads:
        lead = next((l for l in leads if l['id'] == lead_id), None)
        if not lead:
            return jsonify({'error': 'Lead nie istnieje'}), 404

        # 🔒 Dodaj sprawdzenie właściciela
        if lead.get('created_by') != session['user_id']:
            return jsonify({'error': 'Brak uprawnień do edycji tego leada'}), 403

        # Zaktualizuj pola – usuń klucze z wartością '' lub None
        skip_keys = {'id', 'created_by', 'created_name', 'timestamp', 'user_id'}
        for key, value in data.items():
            if key in skip_keys:
                continue
            if value in ['', None, []]:
                lead.pop(key, None)  # usuń klucz jeśli istnieje
            else:
                lead[key] = value

    return jsonify({'message': 'Lead zaktualizowany'}), 200

@investmentmanager_bp.route('/leadhunter/get_lead', methods=['GET'])
def get_lead():
    lead_id = request.args.get('id')
    leads = load_leads()
    lead = next((l for l in leads if str(l['id']) == str(lead_id)), None)

    if not lead:
        return jsonify({'error': 'Lead nie znaleziony'}), 404

    return jsonify(lead)

# -------------------------------
# Endpoint: Pobierz wszystkie leady
# -------------------------------
def normalize_str(s):
    if not isinstance(s, str):
        return ''
    return unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode('utf-8').lower()

def match_estates_to_lead(lead, estates):
    def to_list(val):
        if isinstance(val, list):
            return val
        elif isinstance(val, str):
            return [v.strip() for v in val.split(',') if v.strip()]
        return []
    
    matching = []

    lead_miejscowosci = [normalize_str(m) for m in to_list(lead.get('Miejscowosc'))]
    lead_typy = [normalize_str(t) for t in to_list(lead.get('typ_nieruchomosci'))]
    lead_oferty = [normalize_str(t) for t in to_list(lead.get('typ_oferty'))]

    lead_ceny = []
    cena_raw = lead.get('cena', '')
    if isinstance(cena_raw, str):
        parts = cena_raw.replace('PLN', '').split('-')
        for part in parts:
            part = part.strip().replace(' ', '').replace(',', '.')
            if part.replace('.', '', 1).isdigit():
                lead_ceny.append(float(part))

    lead_pokoje_raw = lead.get('liczba_pokoi', '')
    lead_pokoje = []

    if isinstance(lead_pokoje_raw, list):
        lead_pokoje = [int(p) for p in lead_pokoje_raw if str(p).isdigit()]
    elif isinstance(lead_pokoje_raw, str):
        lead_pokoje = [int(p.strip()) for p in lead_pokoje_raw.split(',') if p.strip().isdigit()]

    for estate in estates:
        estate_miasto = normalize_str(estate.get('Miejscowosc', ''))
        estate_typ = normalize_str(estate.get('Typ_nieruchomosci', ''))
        estate_oferta = normalize_str(estate.get('Typ_oferty', ''))

        miasto_match = not lead_miejscowosci or any(part in estate_miasto for part in lead_miejscowosci)
        typ_match = not lead_typy or any(part in estate_typ for part in lead_typy)
        oferta_match = not lead_oferty or any(part in estate_oferta for part in lead_oferty)

        try:
            cena_val = float(estate.get('Cena'))
        except (TypeError, ValueError):
            cena_val = None

        cena_match = True
        if lead_ceny and cena_val is not None:
            if len(lead_ceny) == 2:
                min_price, max_price = sorted(lead_ceny)
                cena_match = min_price <= cena_val <= max_price
            elif len(lead_ceny) == 1:
                cena_max = lead_ceny[0] * 1.2
                cena_match = cena_val <= cena_max
            else:
                cena_match = False

        try:
            pokoje_val = int(estate.get('Liczba_pokoi'))
        except (TypeError, ValueError):
            pokoje_val = None

        pokoje_match = True
        if lead_pokoje and pokoje_val is not None:
            pokoje_match = pokoje_val in lead_pokoje

        if miasto_match and typ_match and oferta_match and cena_match and pokoje_match:
            matching.append(estate)

    return matching

@investmentmanager_bp.route('/leadhunter/reverse_match_leads', methods=['POST'])
def reverse_match_leads():
    data = request.get_json()
    estate = data.get('estate')
    
    if not estate:
        return jsonify({'error': 'Brak danych nieruchomości'}), 400

    leads = load_leads()

    # Dopasuj leady do danej nieruchomości (odwrócenie logiki)
    matching_leads = []
    for lead in leads:
        matched = match_estates_to_lead(lead, [estate])
        if matched:
            matching_leads.append(lead)

    return jsonify(matching_leads), 200

@investmentmanager_bp.route('/leadhunter/get_leads', methods=['GET'])
def get_leads():
    leads = load_leads()
    estates = get_estates_for_leads(limit=100)

    enriched = []
    for lead in leads:
        lead_copy = lead.copy()
        matched = match_estates_to_lead(lead, estates)
        lead_copy['matching_estates'] = matched
        enriched.append(lead_copy)

    return jsonify(enriched)


@investmentmanager_bp.route('/leadhunter/delete_lead', methods=['POST'])
def delete_lead():
    data = request.get_json()
    lead_id = data.get('id')
    if not lead_id:
        return jsonify({'error': 'Brak ID leada'}), 400

    with _leads_transaction() as leads:
        lead = next((l for l in leads if l['id'] == lead_id), None)

        if not lead:
            return jsonify({'error': 'Lead nie istnieje'}), 404

        # Tylko autor może usunąć
        if lead.get('created_by') != session['user_id']:
            return jsonify({'error': 'Brak uprawnień do usunięcia tego leada'}), 403

        leads[:] = [l for l in leads if l['id'] != lead_id]
    return jsonify({'message': 'Lead usunięty'}), 200
