import sqlite3
import argparse
import json

DB_NAME = 'form_filler.db'
conn = sqlite3.connect(DB_NAME)

def add_website(address):
    try:
        conn.execute("INSERT INTO websites (address) VALUES (?)", (address,))
        conn.commit()
        print(f"Dodano stronę {address}")
    except sqlite3.IntegrityError:
        print(f"Strona już istnieje w bazie!")

def list_websites():
    rows = conn.execute("SELECT id, address, active FROM websites").fetchall()
    for row in rows:
        print(f"[{row[0]}] {row[1]} - {'WŁĄCZONA' if row[2] else 'WYŁĄCZONA'}")

def set_active_status(address, status):
    conn.execute("UPDATE websites SET active = ? WHERE address = ?", (1 if status else 0, address))
    conn.commit()
    print(f"Ustawiono testowanie formularza w witrynie {address}")

def add_data_json(website_address, form_fields_str):
    try:
        form_fields = json.loads(form_fields_str)
    except json.JSONDecodeError:
        print("Nieprawidłowy JSON!")
        return

    conn.execute("INSERT INTO data (website_address, form_fields) VALUES (?, ?)",
                 (website_address, json.dumps(form_fields)))
    conn.commit()

    print(f"Dodano dane formularza dla {website_address}")

def list_data(website_address=None):
    if website_address:
        rows = conn.execute("SELECT id, website_address, form_fields FROM data WHERE website_address = ?", (website_address,)).fetchall()
    else:
        rows = conn.execute("SELECT id, website_address, form_fields FROM data").fetchall()

    for row in rows:
        print(f"[{row[0]}] Strona: {row[1]}")
        print(json.dumps(json.loads(row[2]), indent=2))
        print("---")

def remove_form_data(address):
    cur = conn.execute("DELETE FROM data WHERE website_address = ?", (address,))
    conn.commit()
    if cur.rowcount:
        print(f"Usunięto dane formularza o adresie {address}")
    else:
        print(f"Nie znaleziono danych formularza o adresie {address}")

def cli():
    parser = argparse.ArgumentParser()
    parser.add_argument("--add", help="Dodaj nową witrynę")
    parser.add_argument("--active", nargs=2, metavar=("address", "0|1"), help="Włącz/wyłącz testowanie formularza na witrynie")
    parser.add_argument("--list", action="store_true", help="Pokaż listę witryn")
    parser.add_argument("--add-form-data", nargs=2, metavar=("address", "json_data"), help="Dodaj dane formularza (JSON!)")
    parser.add_argument("--remove-form-data", help="Usuń dane formularza o podanym adresie")
    parser.add_argument("--list-form-data", nargs="?", const="", metavar="address", help="Wypisz dane formularza dla wszystkich stron")

    args = parser.parse_args()

    if args.add:
        add_website(args.add)
    elif args.active:
        set_active_status(args.active[0], bool(int(args.active[1])))
    elif args.list:
        list_websites()
    elif args.add_form_data:
        add_data_json(args.add_form_data[0], args.add_form_data[1])
    elif args.remove_form_data:
        remove_form_data(args.remove_form_data)
    elif args.list_form_data is not None:
        list_data(args.list_form_data if args.list_form_data else None)

if __name__ == "__main__":
    cli()
