import time
import win32com.client
import pandas as pd
from pathlib import Path

OUT_XLSX = Path(r"C:\Temp\GAL_export.xlsx")

def safe_get(obj, attr):
    try:
        return getattr(obj, attr)
    except Exception:
        return None

outlook = win32com.client.Dispatch("Outlook.Application")
ns = outlook.GetNamespace("MAPI")

gal = ns.GetGlobalAddressList()
entries = gal.AddressEntries

rows = []

total = entries.Count
print(f"Počet položek v GAL: {total}")

start = time.perf_counter()
last = start
PROGRESS_EVERY = 100  # každých N položek vypsat rychlost

for i in range(1, total + 1):  # Outlook COM je 1-based
    try:
        entry = entries.Item(i)

        name = safe_get(entry, "Name")
        address = safe_get(entry, "Address")
        entry_type = safe_get(entry, "AddressEntryUserType")

        smtp = None
        job_title = None
        department = None
        company = None
        office = None
        phone = None
        mobile = None

        # Exchange user
        try:
            exch_user = entry.GetExchangeUser()
        except Exception:
            exch_user = None

        if exch_user:
            smtp = safe_get(exch_user, "PrimarySmtpAddress")
            job_title = safe_get(exch_user, "JobTitle")
            department = safe_get(exch_user, "Department")
            company = safe_get(exch_user, "CompanyName")
            office = safe_get(exch_user, "OfficeLocation")
            phone = safe_get(exch_user, "BusinessTelephoneNumber")
            mobile = safe_get(exch_user, "MobileTelephoneNumber")

        # Distribution list
        try:
            exch_dl = entry.GetExchangeDistributionList()
        except Exception:
            exch_dl = None

        if exch_dl and not smtp:
            smtp = safe_get(exch_dl, "PrimarySmtpAddress")

        rows.append({
            "name": name,
            "smtp": smtp,
            "address": address,
            "entry_type": entry_type,
            "job_title": job_title,
            "department": department,
            "company": company,
            "office": office,
            "phone": phone,
            "mobile": mobile,
        })

    except Exception as e:
        rows.append({
            "name": None,
            "smtp": None,
            "error": str(e),
        })

    # průběžný výpis rychlosti
    if i % PROGRESS_EVERY == 0 or i == total:
        now = time.perf_counter()
        elapsed = now - start
        rate = i / elapsed if elapsed else 0
        recent_rate = PROGRESS_EVERY / (now - last) if now > last else 0
        remaining = (total - i) / rate if rate else 0
        print(
            f"  {i}/{total} ({i / total:.0%}) | "
            f"{rate:.1f} pol./s (akt. {recent_rate:.1f}) | "
            f"uplynulo {elapsed:.1f}s | zbývá ~{remaining:.0f}s",
            flush=True,
        )
        last = now

total_elapsed = time.perf_counter() - start
print(
    f"Zpracováno {total} položek za {total_elapsed:.1f}s "
    f"({total / total_elapsed:.1f} pol./s)"
)

df = pd.DataFrame(rows)
df.to_excel(OUT_XLSX, index=False)

print(f"Hotovo: {OUT_XLSX}")