import tkinter as tk
from tkinter import messagebox
import json
import os
import hashlib

USER_FILE ="users.json"
# Create file if not exists
if not os.path.exists(USER_FILE) or os.path.getsize(USER_FILE) == 0:
    with open(USER_FILE, 'w')as f:
        json.dump({},f)
        
def load_users():
    if os.path.getsize(USER_FILE) == 0:
        return {}
    with open(USER_FILE, "r") as f:
        try:
            return json.load(f)
        except json.JSONDecodeError:
            return {}
        
def save_Users(user):
    with open(USER_FILE, "w") as f:
        json.dump(user, f, indent=4)
        
# Function to hash password
def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

def signup():
    username = entry_username.get().strip()
    password = entry_password.get().strip()
    
    if not username or not password:
        messagebox.showerror("Error", "All fields are required!")
        return
    
    users = load_users()
    if username in users:
        messagebox.showerror("Error", "Username already exists!")
        return
    users[username] = hash_password(password)
    save_Users(users)
    messagebox.showinfo("Success", "Account created successfully!")
    
def login():
    username = entry_username.get().strip()
    password = entry_password.get().strip()
    
    users = load_users()
    hashed = hash_password(password)
    if username in users and users[username] == hashed:
        messagebox.showinfo("Success", f"Welcome, {username}!")
    else:
        messagebox.showerror("Error", "Invalid username or password.")
# Tkinter GUI

root = tk.Tk()
root.title("Login / Signup Form")
root.geometry("300x250")
root.config(bg="#f2f2f2")

# Widgets
tk.Label(root, text="Username:", bg="#f2f2f2").pack(pady=5)
entry_username = tk.Entry(root, width=25)
entry_username.pack(pady=5)

tk.Label(root, text="Password:", bg="#f2f2f2").pack(pady=5)
entry_password = tk.Entry(root, width=25, )
entry_password.pack(pady=5)

tk.Button(root, text="Login", command=login, width=10, bg="#4CAF50", fg="white").pack(pady=5)
tk.Button(root, text="signup", command=signup, width=10, bg="#4CAF50", fg="white").pack(pady=5)


root.mainloop()