from flask import Blueprint, request, render_template, redirect, session
import csv
from io import TextIOWrapper
from models import Asset, db
from process_csv import get_csv_data  # Import the CSV processing function
from config import item_attributes  # Import the configuration

# Create a Blueprint for upload
upload_bp = Blueprint('uploadcsv', __name__)

@upload_bp.route('/uploadcsv', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # Check if a file was uploaded
        if 'file' not in request.files:
            return redirect('uploadcsv')

        file = request.files['file']

        # Check if the file is a CSV
        if file.filename == '' or not file.filename.endswith('.csv'):
            return redirect('uploadcsv')

        try:
            # Extract data from the CSV file
            csvdata = get_csv_data(file)

            # Identify the primary attribute
            primary_attrib = next(
                (attrib for attrib, config in item_attributes.items() if config.primary),
                None
            )

            if not primary_attrib:
                return "Primary attribute not defined in configuration."

            # Separate new and existing assets
            new_assets = []
            existing_assets = []
            for row in csvdata:
                primary_value = row[primary_attrib]
                asset_exists = Asset.query.filter_by(**{primary_attrib: primary_value}).first()
                if asset_exists:
                    existing_assets.append(row)
                else:
                    new_assets.append(row)

            session['assets'] = new_assets  # Store new assets in session

            # Redirect to preview page with the CSV data
            return render_template('csv_preview.html', new_assets=new_assets, existing=existing_assets, item_attributes=item_attributes)

        except Exception as e:
            # Handle errors during file processing
            print(f"Error processing CSV file: {str(e)}")
            return redirect('uploadcsv')

    # Render the upload page for GET requests
    return render_template('upload.html')