from datetime import datetime  # Add this import at the top of your file
from flask import render_template, request, redirect, url_for, flash
from app import app, db
from models import Vehicle, WarrantyRegistration
import requests

@app.route('/', methods=['GET', 'POST'])
def register_product():
    if request.method == 'POST':
        vin = request.form.get('vin')
        
        # Debugging output
        print(f"Received VIN: {vin}")
        
        # Use the vPIC API to decode VIN
        try:
            response = requests.get(f'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/{vin}?format=json')
            response.raise_for_status()
            data = response.json()
            
            # Print API response for debugging
            print(f"API Response: {data}")
            
            # Extract vehicle details
            vehicle_data = data.get("Results", [{}])[0]
            make = vehicle_data.get("Make", "Unknown")
            model = vehicle_data.get("Model", "Unknown")
            year = vehicle_data.get("ModelYear", "Unknown")

            # Ensure database session context
            with app.app_context():
                vehicle = Vehicle.query.filter_by(vin=vin).first()
                if not vehicle:
                    # Save vehicle data to the database
                    vehicle = Vehicle(vin=vin, make=make, model=model, year=year)
                    db.session.add(vehicle)
                    db.session.commit()
                else:
                    # Update vehicle data if it exists but has unknown fields
                    if vehicle.make == "Unknown" and make != "Unknown":
                        vehicle.make = make
                    if vehicle.model == "Unknown" and model != "Unknown":
                        vehicle.model = model
                    if vehicle.year == "Unknown" and year != "Unknown":
                        vehicle.year = year
                    db.session.commit()
            
            # Render form with pre-filled vehicle data
            return render_template('register.html', vin=vin, make=make, model=model, year=year)

        except requests.exceptions.RequestException as e:
            print(f"Error during VIN lookup: {e}")
            flash("There was an error retrieving the vehicle data. Please try again.")
            return redirect(url_for('register_product'))
    
    return render_template('register.html')

@app.route('/submit_registration', methods=['POST'])
def submit_registration():
    vin = request.form.get('vin')
    customer_name = request.form.get('customer_name')
    customer_email = request.form.get('customer_email')
    installer_business = request.form.get('installer_business')
    installed_product = request.form.get('installed_product')
    
    # Convert installation_date to a Python date object
    installation_date_str = request.form.get('installation_date')
    installation_date = datetime.strptime(installation_date_str, "%Y-%m-%d").date()  # Convert to date object

    # Debugging output
    print("Form Data Received:")
    print(f"VIN: {vin}")
    print(f"Customer Name: {customer_name}")
    print(f"Customer Email: {customer_email}")
    print(f"Installer Business: {installer_business}")
    print(f"Installed Product: {installed_product}")
    print(f"Installation Date: {installation_date}")

    if not vin or not customer_name or not customer_email or not installer_business or not installed_product or not installation_date:
        flash("Please fill in all fields.")
        return redirect(url_for('register_product'))

    # Ensure database session context
    with app.app_context():
        vehicle = Vehicle.query.filter_by(vin=vin).first()
        if vehicle:
            # Create a new warranty registration
            warranty_registration = WarrantyRegistration(
                vin=vin,
                customer_name=customer_name,
                customer_email=customer_email,
                installer_business=installer_business,
                installed_product=installed_product,
                installation_date=installation_date,  # Pass date object here
                make=vehicle.make,
                model=vehicle.model,
                year=vehicle.year
            )
            db.session.add(warranty_registration)
            db.session.commit()
            flash("Warranty registration submitted successfully.")
        else:
            flash("Vehicle information could not be found. Please verify the VIN.")
            return redirect(url_for('register_product'))

    return redirect(url_for('register_product'))

@app.route('/lookup_warranty', methods=['GET', 'POST'])
def lookup_warranty():
    warranty = None
    if request.method == 'POST':
        vin = request.form.get('vin')
        print(f"Searching for VIN: {vin}")  # Debugging output
        warranty = WarrantyRegistration.query.filter_by(vin=vin).first()
        print(f"Query Result: {warranty}")  # Debugging output
    return render_template('lookup_warranty.html', warranty=warranty)


@app.route('/registrations')
def view_registrations():
    with app.app_context():
        registrations = WarrantyRegistration.query.all()
    return render_template('view_registrations.html', registrations=registrations)
