import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
import fdb
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment
from datetime import date, timedelta
import os

conn = fdb.connect(
    dsn=r'localhost:c:\medicus 3\data\medicus.fdb',
    user='SYSDBA', password='masterkey', charset='win1250'
)
cur = conn.cursor()

zacatek = date(2025, 1, 1)
konec = date.today()
dny = []
d = zacatek
while d <= konec:
    dny.append(d)
    d += timedelta(days=1)

print(f"Počítám {len(dny)} dní ({zacatek} – {konec})...")

vysledky = []
for i, den in enumerate(dny):
    # Počet registrovaných
    cur.execute(f"""
        SELECT COUNT(*) FROM KAR
        WHERE vyrazen = 'N'
        AND EXISTS (
            SELECT id FROM registr r
            JOIN icp i ON r.idicp = i.idicp
            WHERE r.idpac = kar.idpac
              AND r.datum <= '{den}'
              AND (r.datum_zruseni IS NULL OR r.datum_zruseni >= '{den}')
              AND r.priznak IN ('V','D','A')
              AND i.icp = '09305001'
              AND i.odb = '001'
        )
    """)
    pocet = cur.fetchone()[0]

    # Zaregistrovaní tento den
    cur.execute(f"""
        SELECT k.RODCIS, k.PRIJMENI, k.JMENO
        FROM REGISTR r JOIN KAR k ON k.IDPAC = r.IDPAC
        WHERE r.datum = '{den}'
          AND r.priznak IN ('V','D','A')
        ORDER BY k.PRIJMENI, k.JMENO
    """)
    zaregistrovani = [f"{row[0]} {row[1].strip()} {row[2]}" for row in cur.fetchall()]

    # Odregistrovaní tento den
    cur.execute(f"""
        SELECT k.RODCIS, k.PRIJMENI, k.JMENO
        FROM REGISTR r JOIN KAR k ON k.IDPAC = r.IDPAC
        WHERE r.datum_zruseni = '{den}'
        ORDER BY k.PRIJMENI, k.JMENO
    """)
    odregistrovani = [f"{row[0]} {row[1].strip()} {row[2]}" for row in cur.fetchall()]

    vysledky.append((den, pocet, zaregistrovani, odregistrovani))
    if (i + 1) % 30 == 0:
        print(f"  {i+1}/{len(dny)}: {den} → {pocet}")

conn.close()

# Excel
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Registrace"

hlavicka_font = Font(bold=True, color="FFFFFF")
hlavicka_fill = PatternFill("solid", fgColor="2E75B6")
ws.column_dimensions['A'].width = 14
ws.column_dimensions['B'].width = 14
ws.column_dimensions['C'].width = 10
ws.column_dimensions['D'].width = 45
ws.column_dimensions['E'].width = 45

for col, nazev in enumerate(['Datum', 'Registrovaných', 'Změna', 'Zaregistrováno', 'Odregistrováno'], start=1):
    cell = ws.cell(row=1, column=col, value=nazev)
    cell.font = hlavicka_font
    cell.fill = hlavicka_fill
    cell.alignment = Alignment(horizontal='center')

predchozi = None
for row_i, (den, pocet, zaregistrovani, odregistrovani) in enumerate(vysledky, start=2):
    ws.cell(row=row_i, column=1, value=den).number_format = 'DD.MM.YYYY'
    ws.cell(row=row_i, column=2, value=pocet).alignment = Alignment(horizontal='center')

    if predchozi is not None:
        zmena = pocet - predchozi
        cell = ws.cell(row=row_i, column=3, value=zmena)
        cell.alignment = Alignment(horizontal='center')
        if zmena > 0:
            cell.font = Font(color="00AA00", bold=True)
        elif zmena < 0:
            cell.font = Font(color="CC0000", bold=True)
    predchozi = pocet

    if zaregistrovani:
        cell = ws.cell(row=row_i, column=4, value="\n".join(zaregistrovani))
        cell.alignment = Alignment(wrap_text=True, vertical='top')
        cell.font = Font(color="00AA00")

    if odregistrovani:
        cell = ws.cell(row=row_i, column=5, value="\n".join(odregistrovani))
        cell.alignment = Alignment(wrap_text=True, vertical='top')
        cell.font = Font(color="CC0000")

ws.freeze_panes = 'A2'

vystup = os.path.join(os.path.dirname(__file__), 'registrace_2025_dnes.xlsx')
wb.save(vystup)
print(f"\nUloženo: {vystup}")
