# Report generator: feasibility/investigators -> Excel
# Projekt: 77242113UCO2001
# Ulozeni: u:\Dropbox\!!!Days\Downloads Z230\\

import os
import sys
from datetime import datetime
from pymongo import MongoClient
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter

# --- Připojení k MongoDB ---
MONGO_URI = os.environ.get("MONGO_URI", "mongodb://192.168.1.76:27017")
client = MongoClient(MONGO_URI)
db = client["feasibility"]
col = db["investigators"]

# --- Načtení dat ---
docs = list(col.find({}))
print(f"Načteno {len(docs)} záznamů.")

# --- Cílová složka ---
OUTPUT_DIR = r"u:\Dropbox\!!!Days\Downloads Z230"
os.makedirs(OUTPUT_DIR, exist_ok=True)

datum = datetime.now().strftime("%Y%m%d_%H%M")
filename = f"77242113UCO2001_investigators_{datum}.xlsx"
filepath = os.path.join(OUTPUT_DIR, filename)

# --- Definice sloupců ---
# Pořadí: jméno, email, status, kriticka_poznamka, pak ostatní
FIXED_COLS = [
    ("prijmeni",        "Příjmení"),
    ("jmeno",           "Jméno"),
    ("email",           "Email"),
    ("STATUS",          "STATUS"),
    ("kriticka_poznamka", "Kritická poznámka"),
    ("zeme",            "Země"),
    ("pracoviste",      "Pracoviště"),
    ("internet_summary","Internet summary"),
]

# Klíče, které přeskočíme (složité nested objekty)
SKIP_KEYS = {"_id", "excel", "sites_illuminator", "maf", "zdroje", "studie", "Viper_Performance", "Viper_Contacts"}

# Ostatní skalární pole
fixed_keys = {c[0] for c in FIXED_COLS}
extra_keys = set()
for doc in docs:
    for k in doc.keys():
        if k not in fixed_keys and k not in SKIP_KEYS:
            extra_keys.add(k)
extra_keys = sorted(extra_keys)

ALL_COLS = FIXED_COLS + [(k, k) for k in extra_keys]

# --- Barvy podle STATUS ---
def status_color(status):
    if not status:
        return None
    s = status.lower()
    if "nezájem" in s or "nezajem" in s or "nechceme" in s:
        return "FFFFC7CE"   # červená
    if "zájem" in s or "zajem" in s:
        return "FFC6EFCE"   # zelená
    if "nedoručen" in s or "nedorucen" in s:
        return "FFFFEB9C"   # žlutá
    if "email odeslán" in s or "email odeslan" in s:
        return "FFDCE6F1"   # modrá
    return None

# --- Vytvoření workbooku ---
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Investigators"

# Styly
header_font = Font(bold=True, color="FFFFFFFF")
header_fill = PatternFill("solid", fgColor="FF1F4E79")
header_align = Alignment(horizontal="center", vertical="center", wrap_text=True)
cell_align = Alignment(vertical="top", wrap_text=True)
thin = Side(style="thin", color="FFB0B0B0")
border = Border(left=thin, right=thin, top=thin, bottom=thin)

# Záhlaví
for col_idx, (key, label) in enumerate(ALL_COLS, 1):
    cell = ws.cell(row=1, column=col_idx, value=label)
    cell.font = header_font
    cell.fill = header_fill
    cell.alignment = header_align
    cell.border = border

ws.row_dimensions[1].height = 30

# Data
for row_idx, doc in enumerate(docs, 2):
    status_val = str(doc.get("STATUS", "") or "")
    bg = status_color(status_val)

    for col_idx, (key, label) in enumerate(ALL_COLS, 1):
        val = doc.get(key, "")
        # Převod na string pokud je list nebo dict
        if isinstance(val, list):
            val = ", ".join(str(v) for v in val)
        elif isinstance(val, dict):
            val = str(val)
        elif val is None:
            val = ""
        else:
            val = str(val)

        cell = ws.cell(row=row_idx, column=col_idx, value=val)
        cell.alignment = cell_align
        cell.border = border

        if bg:
            cell.fill = PatternFill("solid", fgColor=bg)

# Šířky sloupců
col_widths = {
    "prijmeni": 18, "jmeno": 15, "email": 35,
    "STATUS": 45, "kriticka_poznamka": 60,
    "zeme": 12, "pracoviste": 35, "internet_summary": 60,
}
for col_idx, (key, label) in enumerate(ALL_COLS, 1):
    w = col_widths.get(key, 20)
    ws.column_dimensions[get_column_letter(col_idx)].width = w

# Zmrazení záhlaví
ws.freeze_panes = "A2"

# Autofilter
ws.auto_filter.ref = ws.dimensions

# Uložení
wb.save(filepath)
print(f"Ulozeno: {filepath}")