from flask import Blueprint, request, render_template, redirect, session, flash
from definitions.models import Asset, db
from functions.process_csv import get_csv_data
from functions.validate_values import validate_values
from config import item_attributes

upload_bp = Blueprint('uploadcsv', __name__)

@upload_bp.route('/uploadcsv', methods=['GET', 'POST'])
def upload_file():
    # Check if primary attribute is defined
    primary_attrib = next((attrib for attrib in item_attributes if attrib.primary), None)
    if not primary_attrib:
        flash("Primary attribute not defined in configuration.", "error")
        return redirect(request.url)

    if request.method == 'POST':
        # Check if a file was uploaded
        if 'file' not in request.files:
            flash("No file uploaded.", "error")
            return redirect(request.url)

        file = request.files['file']

        # Check if the file is a CSV
        if file.filename == '' or not file.filename.endswith('.csv'):
            flash("Please upload a valid CSV file.", "error")
            return redirect(request.url)

        try:
            # Extract CSV data
            csvdata = get_csv_data(file)
        except Exception as e:
            flash(f"Error reading CSV file: {str(e)}", "error")
            return redirect(request.url)

        # Validate each row of data
        errors = []
        for i, row in enumerate(csvdata, start=1):
            error = validate_values(row)
            if error:
                errors.append(f"Row {i}: {error}")

        if errors:
            # Pass errors as a list to the template
            return render_template(
                'upload.html',
                errors=errors
            )

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

        # Store new assets in session for further processing
        session['new_assets'] = new_assets
        session['existing_assets'] = existing_assets

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

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