"""Visible administrator-password setup, separate from the terminal."""
import sys
import traceback
from pathlib import Path


def password_error(first, second):
    if len(first) < 12:
        return 'كلمة المرور يجب أن تكون 12 حرفًا أو أكثر.'
    if len(first) > 512:
        return 'كلمة المرور طويلة جدًا؛ الحد الأقصى 512 حرفًا.'
    if first != second:
        return 'كلمتا المرور غير متطابقتين. أعد كتابتهما.'
    return ''


def main():
    import tkinter as tk
    from tkinter import messagebox
    root = tk.Tk()
    root.title('Al Masa Home — Admin password')
    root.geometry('580x510')
    root.minsize(520, 480)
    root.configure(bg='#f6f4ee')
    font = ('Tahoma', 11)
    frame = tk.Frame(root, bg='#f6f4ee', padx=30, pady=20)
    frame.pack(fill='both', expand=True)
    tk.Label(frame, text='الماسة هوم — إعداد كلمة مرور المدير', font=('Tahoma', 15, 'bold'), bg='#f6f4ee', fg='#182638').pack(pady=(0, 12))
    tk.Label(frame, text='اختر كلمة مرور من 12 حرفًا أو أكثر.\nتغيير كلمة المرور لا يحذف المنتجات أو الصور.', font=font, bg='#f6f4ee', justify='right').pack(anchor='e', pady=(0, 12))
    tk.Label(frame, text='كلمة المرور الجديدة', font=font, bg='#f6f4ee').pack(anchor='e')
    first = tk.Entry(frame, show='*', font=font, width=45)
    first.pack(fill='x', ipady=6)
    tk.Label(frame, text='تأكيد كلمة المرور', font=font, bg='#f6f4ee').pack(anchor='e', pady=(10, 0))
    second = tk.Entry(frame, show='*', font=font, width=45)
    second.pack(fill='x', ipady=6)
    visible = tk.BooleanVar(value=False)
    def toggle():
        first.configure(show='' if visible.get() else '*')
        second.configure(show='' if visible.get() else '*')
    tk.Checkbutton(frame, text='إظهار كلمة المرور', variable=visible, command=toggle, font=font, bg='#f6f4ee').pack(anchor='e', pady=8)
    saved = False
    def save():
        nonlocal saved
        error = password_error(first.get(), second.get())
        if error:
            messagebox.showerror('راجع كلمة المرور', error, parent=root)
            return
        button.configure(state='disabled')
        root.update_idletasks()
        try:
            from server import set_password
            set_password(first.get())
        except Exception:
            log = Path(__file__).resolve().parent / 'setup-error.log'
            try:
                log.write_text(traceback.format_exc(), encoding='utf-8')
            except OSError:
                pass
            messagebox.showerror('تعذر الحفظ', 'لم يتم حفظ كلمة المرور. راجع ملف setup-error.log\nأو أرسل صورة رسالة الخطأ في النافذة السوداء.', parent=root)
            traceback.print_exc()
            button.configure(state='normal')
            return
        saved = True
        first.delete(0, 'end')
        second.delete(0, 'end')
        messagebox.showinfo('تم الحفظ', 'تم حفظ كلمة مرور المدير بنجاح.\nشغّل START.bat ثم افتح لوحة الإدارة وسجّل الدخول.', parent=root)
        root.destroy()
    button = tk.Button(frame, text='حفظ كلمة المرور', command=save, bg='#182638', fg='white', font=('Tahoma', 12, 'bold'), padx=20, pady=8)
    button.pack(fill='x', pady=8)
    first.bind('<Return>', lambda event: second.focus_set())
    second.bind('<Return>', lambda event: save())
    first.focus_set()
    root.mainloop()
    return 0 if saved else 2


if __name__ == '__main__':
    try:
        sys.exit(main())
    except Exception:
        traceback.print_exc()
        print('\nPassword setup could not open. Install Python with Tcl/Tk support, then retry.')
        sys.exit(1)
