
from core.utils.packages import application, session, engine
from core.utils.packages.engine import traceError
from flask import Blueprint, render_template, request, flash, redirect, url_for, current_app, jsonify
from flask import session as Session
from flask_login import login_required
from datetime import datetime, timedelta, timezone
import json
from werkzeug.utils import secure_filename
import os
import requests
import hashlib


blueprintname = Blueprint("custom", __name__)
slug = "c"

@blueprintname.route(f"/{slug}/importation")
def importation():
    from core.utils.db import db
    from project.models.production.property import Property
    from sqlalchemy import inspect
    fields = {
        "Id":"id",
        "AllImageUrls":"allImages",
        "Agent Contact Count":"AgentContactCount",
        "Ammenities":"AmmenitiesCommunity",
        "Bathrooms":"Bathrooms",
        "Bedrooms":"Rooms",
        "Cadastre":"Cadastre",
        "Cadastre Number":"CadastreNumber",
        "Comments":"Comments",
        "Commision Value":"CommisionValue",
        "Composite ID":"CompositeID",
        "Condominium Regulation":"CondominiumRegulation",
        "Construction Area":"ConstructionArea",
        "Contract Type":"ContractType",
        "Correo Prueba":"CorreoPrueba",
        "Craiglist":"Craiglist",
        "Customer Agent Contact":"CustomerAgentContact",
        "Customer Info Sent":"CustomerInfoSent",
        "Description":"Description",
        "Description (Es)":"DescriptionEs",
        "Direct Or Indirect":"DirectOrIndirect",
        "Email Request Count":"EmailRequestCount",
        "Encuentra 24":"Encuentra24",
        "Exact Address":"ExactAddress",
        "Featured":"Featured",
        "Features":"Features",
        "Flooring":"Flooring",
        "Floors":"Floors",
        "Número Folio Real":"FolioNoRef",
        "Rent":"ForRent",
        "Sale":"ForSale",
        "Vacacation":"ForVacationRental",
        "Garage Area":"GarageSize",
        "House Number":"HouseNumber",
        "Image":"Image",
        "Import Appliances":"ApplianceImport",
        "Import Attachment Urls":"AttachmentUrlsImport",
        "Import Availability":"AvailabilityImport",
        "Import Community":"CommunityImport",
        "Import Features":"ImportFeatures",
        "Import Field 4":"ImportField4",
        "Import Furnished":"FurnishedImport",
        "Import Image Urls":"ImageUrlsImport",
        "Import Lifestyles":"ImportLifestyles",
        "Import Location":"LocationImport",
        "Import Maintenance Fee":"ImportMaintenanceFee",
        "Import Owner Email":"OwnerEmailImport",
        "Import Owner Name":"OwnerNameImport",
        "Import Owner Phone":"OwnerPhoneImport",
        "Import Realtor Agent":"AgentResponsibleImport",
        "Import Realtor Email":"RealtorEmailImport",
        "Import Realtor Name":"RealtorNameImport",
        "Import Realtor Phone":"RealtorPhoneImport",
        "Import Rental Price":"ImportRentalPrice",
        "Import Sale Price":"ImportSalePrice",
        "Import Status":"StatusImport",
        "Import Sublocation":"SublocationImport",
        "Import Type":"TypeImport",
        "Import WERCR Agent":"ImportWERCRAgent",
        "Independent Agent Email":"IndependentAgentEmail",
        "Independent Agent Name":"IndependentAgentNames",
        "Independent Agent Phone":"IndependentAgentPhone",
        "Indirect View Count":"IndirectViewCount",
        "Inmotico":"Inmotico",
        "Land Use":"LandUse",
        "Latitude":"Latitude",
        "Lifestyles":"Lifestyles",
        "LInks To External Platforms":"LInksToExternalPlatforms",
        "Links To Own Platforms":"LinksToOwnPlatforms",
        "Longitude":"Longitude",
        "Lot Area":"LotArea",
        "Maintenance Fee":"MaintenanceQuota",
        "Min Price":"MinPrice",
        "Neighborhood":"Neighborhood",
        "New Feature":"NewFeature",
        "New Property Type":"NewPropertyType",
        "Number Of Images":"NumberOfImages",
        "Observaciones":"Observaciones",
        "Old Url":"OldUrl",
        "OLX":"OLX",
        "Owner":"OwnerRecord",
        "Owner Email":"OwnerEmail",
        "Owner Name":"OwnerName",
        "Owner Phone":"OwnerPhones",
        "Parking Spaces":"ParkingSpaces",
        "Pdf File (Import)":"PdfFileImport",
        "Pet Friendly":"PetFriendly",
        "Position":"Position",
        "Price Per Meter":"MetersPer",
        "Professional Pictures":"ProfessionalPictures",
        "Project Name":"ProjectName",
        "Property Label":"PropertyLabel",
        "Property Location":"PropertyLocation",
        "UBICACIÓN DANI":"PropertyLocationFinal",
        "Nombre de Propiedad":"PropertyName",
        "Property Status":"PropertyStatus",
        "Property Sublocation":"PropertySublocation",
        "Property Type":"PropertyType",
        "Registration Document":"RegistrationDocument",
        "Rental Price":"RentalPrice",
        "Roofing":"Roofing",
        "Service Rooms":"ServiceRooms",
        "Short Video ID":"ShortVideoID",
        "Show In Recent":"ShowInRecent",
        "Social Media":"SocialMedia",
        "Square Meters":"SquareMeters",
        "Storage Area":"StorageArea",
        "Title":"Title",
        "Title (Es)":"TitleEs",
        "Vacation Rental Price":"VacationRentalPrice",
        "Visit Count":"VisitCount",
        "Visit Count Hold":"VisitCountHold",
        "Year Built":"YearBuilt",
        "Year Of Last Remodel":"YearOfRemodeling",
        "Youtube Url":"YoutubeUrl"
        }

    booleans = ["Featured","ForRent","ForSale","ForVacationRental","PetFriendly","ProfessionalPictures","ShowInRecent"]
    rows = engine.readCSV("project/properties.csv")
    mapper = inspect(Property)
    relationships = mapper.relationships.keys()
    object_ids = [int(row["Id"]) for row in rows if row.get("Id")]
    try:
        for row in rows:
            property = Property()
            for key, value in fields.items():
                if value in relationships:
                    print(f"Skipping relationship field {key}: {value}")
                    continue
                valueCSV = row.get(key)
                if valueCSV is not None and valueCSV != "":
                    if value in booleans:
                        valueCSV = True if valueCSV.lower() == 'yes' else False
                    setattr(property, value, valueCSV)
                print(f"Processing field {key}: {valueCSV}")
            db.session.add(property)
    except Exception as e:
        print(f"Error processing field {key}: {e}")

    try:
        db.session.commit()
    except Exception as e:
        print(f"Error committing to database: {e}")
        db.session.rollback()

    return render_template('frontend/index.html')