"""
001_pruzkum_PN_tabulek.py
=========================
Průzkum Medicus DB – hledáme tabulky a strukturu relacionou s PN
(pracovní neschopnost).

Spustit na Windows:
    python "001_pruzkum_PN_tabulek.py"

Výstup: přehled tabulek s PN v názvu + jejich sloupce + ukázka dat.
"""
import fdb
import datetime

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

# ── 1. Všechny tabulky s "PN" v názvu ─────────────────────────────────────────
print("=" * 60)
print("TABULKY obsahující 'PN' v názvu")
print("=" * 60)

cur.execute("""
    SELECT TRIM(rdb$relation_name)
    FROM rdb$relations
    WHERE rdb$view_blr IS NULL
      AND (rdb$system_flag IS NULL OR rdb$system_flag = 0)
      AND UPPER(rdb$relation_name) CONTAINING 'PN'
    ORDER BY rdb$relation_name
""")
pn_tables = [row[0] for row in cur.fetchall()]

if pn_tables:
    for t in pn_tables:
        print(f"  {t}")
else:
    print("  (žádná)")

# ── 2. Sloupce každé PN tabulky + ukázka dat ──────────────────────────────────
for table in pn_tables:
    print(f"\n{'─' * 60}")
    print(f"TABULKA: {table}")
    print(f"{'─' * 60}")

    # Sloupce
    cur.execute("""
        SELECT TRIM(rf.rdb$field_name),
               f.rdb$field_type,
               f.rdb$field_length,
               rf.rdb$null_flag
        FROM rdb$relation_fields rf
        JOIN rdb$fields f ON rf.rdb$field_source = f.rdb$field_name
        WHERE TRIM(rf.rdb$relation_name) = ?
        ORDER BY rf.rdb$field_position
    """, (table,))
    cols = cur.fetchall()

    # field_type kódy Firebirdu (nejběžnější)
    type_map = {
        7: 'SMALLINT', 8: 'INTEGER', 10: 'FLOAT', 12: 'DATE',
        13: 'TIME', 14: 'CHAR', 16: 'BIGINT', 27: 'DOUBLE',
        35: 'TIMESTAMP', 37: 'VARCHAR', 261: 'BLOB',
    }

    col_names = []
    for c in cols:
        name, ftype, flen, nullable = c
        type_str = type_map.get(ftype, f'type#{ftype}')
        if flen and ftype in (14, 37):
            type_str += f'({flen})'
        null_str = '' if nullable else ' NOT NULL'
        print(f"  {name:<25} {type_str}{null_str}")
        col_names.append(name)

    # Počet řádků
    try:
        cur.execute(f'SELECT COUNT(*) FROM {table}')
        pocet = cur.fetchone()[0]
        print(f"\n  --> Celkem řádků: {pocet}")
    except Exception as e:
        print(f"\n  --> COUNT selhalo: {e}")
        continue

    # Ukázka prvních 5 řádků
    if pocet > 0:
        try:
            cur.execute(f'SELECT FIRST 5 * FROM {table}')
            rows = cur.fetchall()
            print(f"\n  Ukázka (max 5 řádků):")
            header = " | ".join(f"{n[:12]:>12}" for n in col_names)
            print(f"  {header}")
            print(f"  {'-' * len(header)}")
            for row in rows:
                vals = []
                for v in row:
                    if isinstance(v, (datetime.date, datetime.datetime)):
                        vals.append(v.isoformat()[:12])
                    elif isinstance(v, bytes):
                        vals.append(f'<blob {len(v)}B>')
                    elif v is None:
                        vals.append('NULL')
                    else:
                        vals.append(str(v)[:12])
                print(f"  {' | '.join(f'{v:>12}' for v in vals)}")
        except Exception as e:
            print(f"  Ukázka selhala: {e}")

# ── 3. Hledáme i tabulky s "NESCHOP" nebo "NESCHOPENK" ────────────────────────
print(f"\n{'=' * 60}")
print("TABULKY s 'NESCHOP' nebo 'PRACOV' nebo 'SICK' v názvu")
print("=" * 60)

cur.execute("""
    SELECT TRIM(rdb$relation_name)
    FROM rdb$relations
    WHERE rdb$view_blr IS NULL
      AND (rdb$system_flag IS NULL OR rdb$system_flag = 0)
      AND (
          UPPER(rdb$relation_name) CONTAINING 'NESCHOP'
          OR UPPER(rdb$relation_name) CONTAINING 'PRACOV'
          OR UPPER(rdb$relation_name) CONTAINING 'SICK'
      )
    ORDER BY rdb$relation_name
""")
extra = [row[0] for row in cur.fetchall()]
if extra:
    for t in extra:
        print(f"  {t}")
else:
    print("  (žádná)")

# ── 4. Rychlý přehled – tabulky s datem "OD/DO" nebo "ZACATEK/KONEC" ──────────
print(f"\n{'=' * 60}")
print("SLOUPCE: hledáme 'DATPN', 'DATDO', 'DATUM_DO' v celé DB")
print("=" * 60)

cur.execute("""
    SELECT TRIM(rf.rdb$relation_name), TRIM(rf.rdb$field_name)
    FROM rdb$relation_fields rf
    JOIN rdb$relations r ON rf.rdb$relation_name = r.rdb$relation_name
    WHERE (r.rdb$system_flag IS NULL OR r.rdb$system_flag = 0)
      AND r.rdb$view_blr IS NULL
      AND (
          UPPER(rf.rdb$field_name) CONTAINING 'DATPN'
          OR UPPER(rf.rdb$field_name) = 'DATDO'
          OR UPPER(rf.rdb$field_name) CONTAINING 'DATUM_DO'
          OR UPPER(rf.rdb$field_name) CONTAINING 'DAT_DO'
          OR UPPER(rf.rdb$field_name) CONTAINING 'PN'
      )
    ORDER BY rf.rdb$relation_name, rf.rdb$field_name
""")
hits = cur.fetchall()
if hits:
    for tab, col in hits:
        print(f"  {tab:<30} {col}")
else:
    print("  (nic nenalezeno)")

cur.close()
conn.close()
print(f"\n{'=' * 60}")
print("Průzkum dokončen.")
