from flask import current_app, request, jsonify, session
from InvestmentManager import investmentmanager_bp
from InvestmentManager.middleware.access import note_visible_to
from modules.core.agent_directory_queries import list_active_agent_ids
from modules.core import storage_paths
from modules.core.error_responses import log_internal_error
from modules.core.json_store import JsonStoreError, locked_json, read_json, write_json_atomic
import os
import json
from datetime import datetime
from InvestmentManager.routes.alerts_system import push_alert

# --------------------------------------------
# ŚCIEŻKI I INICJALIZACJA DANYCH
# --------------------------------------------

# Ustalanie ścieżek do folderu i plików z notatkami i powiadomieniami --
# resolved on every call (not at import) so DATA_DIR from .env is honoured.
# Folders and files are created on first write; readers treat a missing
# file as empty.
def _notes_path():
    return str(storage_paths.knowledge_center_notes_path())


def _notifications_path():
    return str(storage_paths.knowledge_center_notifications_path())


def _backup_folder():
    return str(storage_paths.knowledge_center_backups_dir())

# --------------------------------------------

# --------------------------------------------
# BACKUP - zapisywanie kopii zapasowej all_notes.json
# --------------------------------------------
def backup_notes():
    """
    Tworzy kopię zapasową pliku all_notes.json w folderze backups.
    Przechowuje maksymalnie 10 najnowszych backupów.
    """
    notes_path = _notes_path()
    if not os.path.exists(notes_path):
        return

    backup_folder = _backup_folder()
    os.makedirs(backup_folder, exist_ok=True)

    # Nazwa pliku backupu z timestampem
    # mikrosekundy: kilka zapisów w jednej sekundzie nie nadpisują jednej kopii (stare nazwy sortują się przed nowymi)
    backup_name = f"all_notes_backup_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}.json"
    backup_path = os.path.join(backup_folder, backup_name)

    # Zapis kopii
    with open(notes_path, 'r', encoding='utf-8') as src, \
         open(backup_path, 'w', encoding='utf-8') as dst:
        dst.write(src.read())

    # Usuwanie najstarszych backupów (zostawiamy tylko 10 najnowszych)
    backups = sorted(
        [f for f in os.listdir(backup_folder) if f.startswith("all_notes_backup_")],
        reverse=True
    )
    for old_backup in backups[10:]:
        try:
            os.remove(os.path.join(backup_folder, old_backup))
        except Exception as e:
            print(f"Nie udało się usunąć starego backupu {old_backup}: {e}")

# --------------------------------------------
    
# --------------------------------------------
# FUNKCJA: Pobierz wszystkie ID agentów z bazy danych
# --------------------------------------------

def get_all_agent_ids(exclude_user_id=None):
    """
    Zwraca listę wszystkich ID agentów z bazy danych.
    Można wykluczyć jednego użytkownika (np. aktualnie zalogowanego).
    """
    agent_ids = []

    try:
        agent_ids = list_active_agent_ids()

        if exclude_user_id is not None:
            agent_ids = [uid for uid in agent_ids if uid != exclude_user_id]

    except Exception as e:
        # Contract kept (an empty list: the caller's note/comment is already saved and must not fail), but the failure is no longer
        # silent: ERROR with traceback and request_id, so a lost notification round is visible in the error log.
        log_internal_error("knowledge_center.get_all_agent_ids (notification recipients unknown, none will be notified)", e)

    return agent_ids

# --------------------------------------------

# --------------------------------------------
# FUNKCJE POMOCNICZE - NOTATKI
# --------------------------------------------

def load_notes():
    """Wszystkie notatki ([] gdy plik jeszcze nie istnieje). Uszkodzony plik => JsonStoreCorrupt (HTTP 503), nigdy pusta lista."""
    return read_json(_notes_path(), list)

def save_notes(notes):
    """Atomowo zastępuje cały plik. Trasy zmieniają notatki wyłącznie przez `_notes_transaction()`."""
    write_json_atomic(_notes_path(), notes)

def _side_effect_failed(what, error):
    """Notifications / alerts are secondary to the note or comment, which is already committed. A damaged or busy secondary
    store is logged loudly and its own endpoints keep failing closed (503); it must not turn a saved note into an error
    response (the user would retry and create a duplicate)."""
    current_app.logger.error('Knowledge Center: nie zapisano (%s): %s [%s]', what, error, getattr(error, 'code', ''))


def _push_alert_best_effort(**kwargs):
    try:
        push_alert(**kwargs)
    except JsonStoreError as exc:
        _side_effect_failed(f"alert dla użytkownika {kwargs.get('user_id')}", exc)


def _notes_transaction():
    """Jeden read-modify-write pliku all_notes.json pod blokadą międzyprocesową (modules/core/json_store.py)."""
    return locked_json(_notes_path(), list)

# --------------------------------------------

# --------------------------------------------
# ENDPOINT: Dodanie lub edycja notatki
# --------------------------------------------

@investmentmanager_bp.route('/knowledge/add_note', methods=['POST'])
def add_note():
    user_id = session['user_id']
    data = request.json

    edit_mode = data.get("edit_mode", False)
    original_ts = data.get("original_timestamp")

    # Tworzenie nowej notatki
    new_note = {
        "title": data.get("title", "").strip(),
        "content": data.get("content", "").strip(),
        "timestamp": datetime.now().isoformat(),
        "author_id": user_id,
        "author_name": session.get("first_name", "") + " " + session.get("last_name", ""),
        "private": data.get("is_private", True),
        "comments": []
    }

    # Jedna transakcja na pliku notatek: edycja widzi aktualne komentarze, nic nie jest zapisane po błędzie / 404.
    with _notes_transaction() as notes:
        # Tryb edycji: wyszukaj istniejącą notatkę użytkownika i zaktualizuj
        if edit_mode and original_ts:
            for note in notes:
                if note.get("timestamp") == original_ts and note.get("author_id") == user_id:
                    existing_comments = note.get("comments", [])
                    note.update({
                        "title": new_note["title"],
                        "content": new_note["content"],
                        "private": new_note["private"],
                        "timestamp": new_note["timestamp"],
                        "comments": existing_comments
                    })
                    break
            else:
                return jsonify({"error": "Nie znaleziono notatki do edycji."}), 404
        else:
            # Tryb dodania nowej notatki
            notes.insert(0, new_note)

        backup_notes()   # kopia stanu sprzed zmiany (plik jest jeszcze stary: zapis następuje po wyjściu z bloku)

    # Powiadomienia i alerty to osobne, niezagnieżdżone transakcje (inne pliki) - tylko dla notatki publicznej.
    if not new_note["private"]:
        other_users = get_all_agent_ids(exclude_user_id=user_id)

        try:
            with _notifications_transaction() as notifications:
                if edit_mode:
                    # Powiadomienie o edycji notatki
                    for uid in other_users:
                        notifications.append({
                            "user_id": uid,
                            "type": "note_edited",
                            "note_id": new_note["timestamp"],
                            "title": new_note["title"] + " (edytowana)",
                            "timestamp": new_note["timestamp"],
                            "read": False
                        })
                else:
                    # Powiadomienie o nowej notatce
                    for uid in other_users:
                        notifications.append({
                            "user_id": uid,
                            "type": "new_note",
                            "note_id": new_note["timestamp"],
                            "title": new_note["title"],
                            "timestamp": new_note["timestamp"],
                            "read": False
                        })
        except JsonStoreError as exc:
            _side_effect_failed('powiadomienia o notatce', exc)

        # 🔔 Alert do innych użytkowników o nowej publicznej notatce
        agent_name = session.get("first_name", "") + " " + session.get("last_name", "")
        short_content = new_note["content"][:100] + "..." if len(new_note["content"]) > 100 else new_note["content"]

        for uid in other_users:
            _push_alert_best_effort(
                user_id=uid,
                message=f"📝 {agent_name} dodał nową notatkę: „{new_note['title']}”",
                level="info",
                metadata={
                    "Data": new_note["timestamp"],
                    "ID agenta": user_id,
                    "Agent": agent_name,
                    "Tytuł notatki": new_note["title"],
                    "Treść": short_content
                }
            )

    return jsonify({"message": "Notatka zapisana"}), 200

# --------------------------------------------

# --------------------------------------------
# ENDPOINT: Usuwanie notatki
# --------------------------------------------

@investmentmanager_bp.route('/knowledge/delete_note', methods=['POST'])
def delete_note():
    user_id = session['user_id']
    data = request.json
    timestamp = data.get('timestamp')

    if not timestamp:
        return jsonify({'error': 'Brak znacznika czasu'}), 400

    # Usuwanie notatki należącej do użytkownika
    with _notes_transaction() as notes:
        remaining = [n for n in notes if not (n.get('timestamp') == timestamp and n.get('author_id') == user_id)]
        if len(remaining) != len(notes):
            backup_notes()          # kopia stanu sprzed usunięcia
            notes[:] = remaining

    return jsonify({'message': 'Notatka usunięta'}), 200

# --------------------------------------------

# --------------------------------------------
# ENDPOINT: Pobranie listy notatek
# --------------------------------------------

@investmentmanager_bp.route('/knowledge/get_notes', methods=['GET'])
def get_notes():
    user_id = session['user_id']
    notes = load_notes()

    # Oddzielenie notatek prywatnych i publicznych
    private_notes = [n for n in notes if n.get('author_id') == user_id]
    public_notes = [n for n in notes if not n.get('private')]

    # Wczytaj powiadomienia
    notifications = load_notifications()

    # Oddziel powiadomienia wg typu
    highlighted_notes_edits = [
        n['note_id'] for n in notifications
        if n['user_id'] == user_id and not n['read'] and n['type'] in ['new_note', 'note_edited']
    ]

    highlighted_notes_comments = [
        n['note_id'] for n in notifications
        if n['user_id'] == user_id and not n['read'] and n['type'] == 'new_comment'
    ]

    return jsonify({
        "private": private_notes,
        "public": public_notes,
        "highlighted_notes_edits": highlighted_notes_edits,
        "highlighted_notes_comments": highlighted_notes_comments
    })

# --------------------------------------------

# --------------------------------------------
# ENDPOINT: Pobranie komentarzy do notatki
# --------------------------------------------

@investmentmanager_bp.route('/knowledge/get_comments/<note_ts>', methods=['GET'])
def get_comments(note_ts):
    notes = load_notes()
    user_id = session['user_id']
    for note in notes:
        if note.get("timestamp") == note_ts and note_visible_to(note, user_id):
            return jsonify(note.get("comments", [])), 200

    return jsonify([]), 404

# --------------------------------------------

# --------------------------------------------
# ENDPOINT: Dodanie komentarza do notatki
# --------------------------------------------

@investmentmanager_bp.route('/knowledge/add_comment', methods=['POST'])
def add_comment():
    user_id = session['user_id']
    data = request.json
    note_ts = data.get('note_timestamp')
    comment_text = data.get('comment', '').strip()

    if not note_ts or not comment_text:
        return jsonify({'error': 'Brak danych'}), 400

    commented = None
    with _notes_transaction() as notes:
        for note in notes:
            if note.get("timestamp") == note_ts and note_visible_to(note, user_id):
                # Dodanie komentarza do notatki (do AKTUALNEGO stanu pliku, pod blokadą)
                note.setdefault("comments", []).append({
                    "author_id": user_id,
                    "author_name": session.get("first_name", "") + " " + session.get("last_name", ""),
                    "comment": comment_text,
                    "timestamp": datetime.now().isoformat()
                })
                backup_notes()   # kopia stanu sprzed zmiany
                commented = {
                    "private": note.get("private"),
                    "title": note.get("title"),
                    "author_id": note.get("author_id"),
                }
                break

    if commented is None:
        return jsonify({"error": "Nie znaleziono notatki"}), 404

    # Powiadomienia i alert to osobne transakcje (inne pliki), po zatwierdzeniu komentarza.
    # (private notes: nobody else may see them, so no notification carrying the title)
    other_users = [] if commented["private"] else get_all_agent_ids(exclude_user_id=user_id)
    if other_users:
        try:
            with _notifications_transaction() as notifications:
                for uid in other_users:
                    notifications.append({
                        "user_id": uid,
                        "type": "new_comment",
                        "note_id": note_ts,
                        "title": commented["title"] if commented["title"] is not None else "Notatka",
                        "timestamp": datetime.now().isoformat(),
                        "read": False
                    })
        except JsonStoreError as exc:
            _side_effect_failed('powiadomienia o komentarzu', exc)

    # 🔔 ALERT dla autora notatki
    note_author_id = commented["author_id"]
    if note_author_id != user_id:
        agent_name = session.get("first_name", "") + " " + session.get("last_name", "")
        _push_alert_best_effort(
            user_id=note_author_id,
            message=f"📬 {agent_name} skomentował/a Twoją notatkę: „{commented['title'] if commented['title'] is not None else 'Bez tytułu'}”",
            level="info",
            metadata={
                "Data komentarza": note_ts,
                "ID agenta": user_id,
                "Agent": agent_name
            }
        )

    return jsonify({"message": "Komentarz zapisany"}), 200

# --------------------------------------------

# --------------------------------------------
# FUNKCJE POMOCNICZE - POWIADOMIENIA
# --------------------------------------------

def load_notifications():
    """Wszystkie powiadomienia ([] gdy plik nie istnieje). Uszkodzony plik => JsonStoreCorrupt (HTTP 503), nigdy pusta lista."""
    return read_json(_notifications_path(), list)

def save_notifications(notifications):
    """Atomowo zastępuje cały plik. Trasy zmieniają powiadomienia wyłącznie przez `_notifications_transaction()`."""
    write_json_atomic(_notifications_path(), notifications)

def _notifications_transaction():
    """Jeden read-modify-write pliku notifications.json (wspólny dla wszystkich agentów) pod blokadą międzyprocesową."""
    return locked_json(_notifications_path(), list)

# --------------------------------------------

# --------------------------------------------
# ENDPOINT: Pobranie powiadomień użytkownika
# --------------------------------------------

@investmentmanager_bp.route('/knowledge/get_notifications', methods=['GET'])
def get_notifications():
    user_id = session['user_id']
    notifications = load_notifications()

    # Filtrowanie powiadomień nieprzeczytanych dla użytkownika
    user_notifications = [n for n in notifications if n['user_id'] == user_id and not n['read']]
    return jsonify(user_notifications)

# --------------------------------------------

# --------------------------------------------
# ENDPOINT: Oznacz powiadomienia jako przeczytane
# --------------------------------------------

@investmentmanager_bp.route('/knowledge/mark_notifications_read', methods=['POST'])
def mark_notifications_read():
    user_id = session['user_id']
    data = request.get_json()
    note_id = data.get('note_id')
    notif_type = data.get('type')  # może być np. 'new_comment', 'note_edited', 'both' lub None

    updated_count = 0
    with _notifications_transaction() as notifications:
        new_notifications = []

        for n in notifications:
            if n['user_id'] != user_id:
                new_notifications.append(n)
                continue

            should_remove = False

            if note_id and notif_type == 'both':
                if n['note_id'] == note_id and n['type'] in ('new_comment', 'note_edited', 'new_note'):
                    should_remove = True
            elif note_id and notif_type:
                if n['note_id'] == note_id and n['type'] == notif_type:
                    should_remove = True
            elif not note_id and not notif_type:
                should_remove = True

            if should_remove:
                updated_count += 1
            else:
                new_notifications.append(n)

        notifications[:] = new_notifications

    return jsonify({'message': f'Oznaczono i usunięto: {updated_count} powiadomień'})


