"""Cookie debug tool — run with: python3 debug_cookies.py"""

import glob
import os
import shutil
import sqlite3
import tempfile
import time

FIREFOX_COOKIE_PATHS = [
    "~/.mozilla/firefox/*/cookies.sqlite",
    "~/snap/firefox/common/.mozilla/firefox/*/cookies.sqlite",
    "~/.var/app/org.mozilla.firefox/.mozilla/firefox/*/cookies.sqlite",
    "~/.var/app/org.mozilla.firefox/config/mozilla/firefox/*/cookies.sqlite",
]

SEPARATOR = "-" * 70


def main():
    print(SEPARATOR)
    print("Firefox Cookie Debug")
    print(SEPARATOR)

    # ── 1. Find all DB files ──────────────────────────────────────────────────
    all_dbs = []
    for pattern in FIREFOX_COOKIE_PATHS:
        expanded = os.path.expanduser(pattern)
        matches = glob.glob(expanded)
        print(f"\nPattern: {pattern}")
        if matches:
            for m in matches:
                print(f"  FOUND: {m}")
                all_dbs.append(m)
        else:
            print(f"  (keine Treffer)")

    print(f"\n{SEPARATOR}")
    print(f"Gesamt: {len(all_dbs)} cookies.sqlite Datei(en)")
    print(SEPARATOR)

    if not all_dbs:
        print("\nKeine Firefox-Profile gefunden.")
        print("Ist Firefox installiert? (Standard, Snap, oder Flatpak?)")
        return

    # ── 2. Read tralgo.app cookies from each DB ───────────────────────────────
    now = int(time.time())

    for db_path in all_dbs:
        print(f"\nDB: {db_path}")
        tmp = None
        try:
            tmp = tempfile.mktemp(suffix="_debug.sqlite")
            shutil.copy2(db_path, tmp)
            conn = sqlite3.connect(f"file:{tmp}?mode=ro", uri=True)
            try:
                cur = conn.cursor()

                # All tralgo.app cookies
                cur.execute(
                    "SELECT name, value, expiry, host FROM moz_cookies "
                    "WHERE host LIKE '%tralgo%' ORDER BY name"
                )
                all_rows = cur.fetchall()

                # Only auth cookies the app needs
                cur.execute(
                    "SELECT name, value, expiry FROM moz_cookies "
                    "WHERE host LIKE '%tralgo.app%' "
                    "AND (name LIKE 'wordpress_logged_in%' "
                    "     OR name LIKE 'wp2fa_device%')"
                )
                auth_rows = cur.fetchall()
            finally:
                conn.close()

            if not all_rows:
                print("  Keine tralgo.app Cookies gefunden.")
            else:
                print(f"  Alle tralgo.app Cookies ({len(all_rows)} Stück):")
                for name, value, expiry, host in all_rows:
                    expired = expiry < now
                    exp_str = (f"abgelaufen seit {now - expiry}s"
                               if expired else f"gültig noch {expiry - now}s")
                    print(f"    [{exp_str:>30}]  {name[:60]}")

            if auth_rows:
                print(f"\n  Auth-Cookies für GizerBridge ({len(auth_rows)} Stück):")
                for name, value, expiry in auth_rows:
                    expired = expiry < now
                    status = "ABGELAUFEN" if expired else "OK"
                    print(f"    [{status}] {name[:60]}")
                    print(f"           Wert: {value[:60]}...")
            else:
                print("\n  FEHLER: Keine Auth-Cookies (wordpress_logged_in / wp2fa_device).")
                print("  Lösung: Firefox öffnen → tralgo.app → einloggen →")
                print("          'Für 30 Tage merken' aktivieren.")

        except Exception as e:
            print(f"  Fehler beim Lesen: {e}")
        finally:
            if tmp and os.path.exists(tmp):
                try:
                    os.unlink(tmp)
                except OSError:
                    pass

    # ── 3. Final verdict ──────────────────────────────────────────────────────
    print(f"\n{SEPARATOR}")
    from cookie_reader import find_cookies
    cookies, err = find_cookies()
    if err:
        print(f"Ergebnis: FEHLER — {err}")
    else:
        print(f"Ergebnis: OK — {len(cookies)} Auth-Cookie(s) bereit")
        for name in cookies:
            print(f"  {name[:60]}")
    print(SEPARATOR)


if __name__ == "__main__":
    main()
