import cv2
import numpy as np
import os
import datetime
import csv
import requests

# Load Haar Cascades for face and eye detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")

try:
    recognizer = cv2.face.LBPHFaceRecognizer_create()
except AttributeError:
    print("Error: OpenCV contrib package is missing. Install with: pip install opencv-contrib-python")
    exit()

# File Paths
API_ENDPOINT = "https://community.scrubbed.net:8080/api/checkin"
FACE_DIR = "registered_faces"
LOG_FILE = "attendance_log.csv"
MODEL_FILE = "face_recognizer.yml"
USER_ID_FILE = "last_user_id.txt"

def preprocess_face(face_img):
    """Preprocess face images by applying histogram equalization and Gaussian blur for better contrast and noise reduction."""
    face_img = cv2.resize(face_img, (100, 100))
    face_img = cv2.GaussianBlur(face_img, (3, 3), 0)
    face_img = cv2.equalizeHist(face_img)
    return face_img

def collect_training_data(user_id):
    """Captures face images for training, ensuring variations (with glasses, different angles)."""
    user_folder = os.path.join(FACE_DIR, user_id)
    os.makedirs(user_folder, exist_ok=True)
    cap = cv2.VideoCapture(0)
    count = 0
    while count < 70:  # Capture more images for better training
        ret, frame = cap.read()
        if not ret:
            break
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=8, minSize=(50, 50))
        for (x, y, w, h) in faces:
            face_img = gray[y:y + h, x:x + w]
            face_img = preprocess_face(face_img)
            cv2.imwrite(os.path.join(user_folder, f"{count}.jpg"), face_img)
            count += 1
        cv2.imshow("Face Registration", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cap.release()
    cv2.destroyAllWindows()

def train_face_recognizer():
    """Trains LBPH face recognizer with additional preprocessing for better accuracy."""
    faces, labels = [], []
    for user_id in os.listdir(FACE_DIR):
        user_folder = os.path.join(FACE_DIR, user_id)
        for filename in os.listdir(user_folder):
            img_path = os.path.join(user_folder, filename)
            img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
            if img is None:
                continue
            img = preprocess_face(img)
            faces.append(img)
            labels.append(int(user_id))
    if not faces:
        print("No training data found.")
        return
    recognizer.train(faces, np.array(labels))
    recognizer.save(MODEL_FILE)
    print("Training complete.")

def recognize_user():
    """Recognizes a user even if wearing glasses or has slight appearance changes."""
    if not os.path.exists(MODEL_FILE):
        print("Error: Model file not found. Train the model first.")
        return
    recognizer.read(MODEL_FILE)
    cap = cv2.VideoCapture(0)
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=8, minSize=(50, 50))
        for (x, y, w, h) in faces:
            face_img = gray[y:y + h, x:x + w]
            face_img = preprocess_face(face_img)
            user_id, confidence = recognizer.predict(face_img)
            if confidence < 70:  # Adjusted threshold for better accuracy
                text = f"User: {user_id} (Acc: {round(confidence, 2)}%)"
                log_attendance(user_id)
                color = (0, 255, 0)
            else:
                text = "Unknown"
                color = (0, 0, 255)
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2, cv2.LINE_AA)
        cv2.imshow("Face Recognition", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cap.release()
    cv2.destroyAllWindows()

def log_attendance(user_id):
    """Logs attendance while ensuring a single check-in and check-out per day."""
    now = datetime.datetime.now()
    timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
    if not os.path.exists(LOG_FILE):
        with open(LOG_FILE, "w", newline="") as file:
            writer = csv.writer(file)
            writer.writerow(["Timestamp", "User ID", "Status"])
    with open(LOG_FILE, "a", newline="") as file:
        writer = csv.writer(file)
        writer.writerow([timestamp, user_id, "Check-in"])
        send_post_request(user_id)

def send_post_request(user_id):
    """Sends attendance to API."""
    payload = {"user_id": user_id}
    headers = {"Content-Type": "application/json"}
    try:
        response = requests.post(API_ENDPOINT, json=payload, headers=headers)
        if response.status_code == 200:
            print(f"✅ Successfully sent attendance for User {user_id} to API.")
        else:
            print(f"⚠️ Failed. Status: {response.status_code}, Response: {response.text}")
    except requests.exceptions.RequestException as e:
        print(f"❌ Error sending attendance: {e}")

if __name__ == "__main__":
    while True:
        print("\n1: Register User\n2: Train Model\n3: Recognize Face\n4: Exit")
        choice = input("Choose and option: ")
        if choice == "1":
            collect_training_data(input("Enter user ID: "))
        elif choice == "2":
            train_face_recognizer()
        elif choice == "3":
            recognize_user()
        elif choice == "4":
            break
        else:
            print("Invalid choice. Try again.")
