"""
This script is used to pull together some case studies for the Parity Projects comparison
"""

import pandas as pd
from backend.SearchEpc import SearchEpc
from dotenv import load_dotenv
import os

load_dotenv("backend/.env")
EPC_AUTH_TOKEN = os.getenv("EPC_AUTH_TOKEN")

parity_measures = pd.read_excel(
    "/Users/khalimconn-kowlessar/Documents/hestia/Places For People/Parity Sample All Addresses and Measures.xlsx",
    sheet_name="Total Measures"
)

solar_measures = parity_measures[parity_measures["Category"] == "SolarPV"]

example_1 = parity_measures[
    parity_measures["Address Id (used by website)"] == 6125299
    ].copy()

config = {
    "address": "14 Victoria Road",
    "postcode": "BD20 8SY",
    "uprn": 100050346517
}

# Point 1:
# Parity tends to re-score the EPCs, even if they're extrememly recent.
# For example for '14, Victoria Road, Cross Hills, KEIGHLEY, North Yorkshire, ENGLAND, BD20 8SY'
# The most recent EPC was done 15 May 2023, and landed at a 66D, however for some reason, parity re-score this
# home to be a 63.91. It's unclear why this is done

example_1_measures = example_1[["MeasureGroupName", "Individual SAP increase"]].copy()
# - LEDS: 0.25 SAP points
# - 300mm of loft insulation from 200mm: 0.43 SAP points - where is this deduced from? Since the latest survey
# indicates 250mm insulation in place
# - Check construction of unknown party wall and fill cavity if appropriate: 0.12 SAP points (highly speculative,
# not based on any data)
# - Block open chimneys: 1.61 SAP points - latest survey showed 0 open fireplaces
# - ASHP (45 degree emitters) with enhanced existing radiator central heating and hot water, from E rated gas boiler
# 6.38 SAP points
# - 4kWp PV array south and 30 degree pitch with no shading: 30.24 SAP points

# Notes on solar - 30.34 seems like a lot
# 400 watt is the solar panel output
# Let's do a test for this property
# This would be 10 solar panels
# Using typical solar panel dimensions, this would be 19.63555m2 of roof space
# The area of the roof is between 60 - 64.5 m2 (we use a API to get the roof data), implying only
# around 30% of the roof is covered by solar panels
# Using our machine learning model to simulate the impact of this on SAP, this would more likely result in
# a

from utils.s3 import read_dataframe_from_s3_parquet

training_data = read_dataframe_from_s3_parquet(
    bucket_name="retrofit-data-dev",
    file_key="sap_change_model/2024-06-09-10-36-53/dataset_rooms.parquet"
)
# Look for properties where the only difference is solar
ending_cols = [
    c for c in training_data.columns if "_ending" in c and "photo_supply" not in c
]
ending_cols = [
    c for c in ending_cols if
    c not in ["sap_ending", "heat_demand_ending", "carbon_ending", "transaction_type_ending", "days_to_ending"]
]

column_pairs = {}
for col in ending_cols:
    starting = col.split("_ending")[0]
    if starting + "_starting" in training_data.columns:
        starting_col = starting + "_starting"
    else:
        starting_col = starting

    column_pairs[col] = starting_col

filtered = training_data.copy()
# Take rows that had solar installs
filtered = filtered[filtered["photo_supply_ending"] != filtered["photo_supply_starting"]]
for ending_col, starting_col in column_pairs.items():
    filtered = filtered[filtered[ending_col] == filtered[starting_col]]
    print(f"ending_col: {ending_col}, filtered shape: {filtered.shape}")

avg_change = filtered.groupby("photo_supply_ending")["rdsap_change"].mean().reset_index()

# I've take every single case of there being two EPCs for a property, where the only difference between the first
# and second is the solar installation. This is 2692 properties, across the UK. In only 4 instances has this resulted in
# 30 or more SAP points


# Some functions based on the SAP methodology:
import numpy as np

total_floor_area = 50
occupants = calculate_occupants(total_floor_area)
appliances_energy_use = estimate_electrical_appliances(occupants, total_floor_area)
cooking_energy_use = estimate_cooking(occupants)


def calculate_occupants(total_floor_area):
    """
    From Table 1b
    :param total_floor_area:
    :return:
    """
    return 1 + (1.76 * (1 - np.exp(-0.000349 * (total_floor_area - 13.9) * (total_floor_area - 13.9))) + 0.0013 * (
        total_floor_area - 13.9))


def estimate_electrical_appliances(occupants, total_floor_area):
    """
    From seciont L2 Electrical appliances
    :param occupants:
    :param total_floor_area:
    :return:
    """
    e_a = 207.8 * np.power(total_floor_area * occupants, 0.4717)

    days_in_month = {
        1: 31,
        2: 28,
        3: 31,
        4: 30,
        5: 31,
        6: 30,
        7: 31,
        8: 31,
        9: 30,
        10: 31,
        11: 30,
        12: 31
    }

    eam = 0
    for m in range(1, 13):
        nm = days_in_month[m]
        eam += e_a * (1 + 0.157 * np.cos(2 * np.pi * (m - 1.78) / 12)) * nm / 365

    return eam


def estimate_cooking(occupants):
    """
    From section L3 Cooking
    :param occupants:
    :return:
    """

    return 35 + 7 * occupants


primary_energy_per_m2 = 288  # kWh/m2 per year
primary_energy_regulated = primary_energy_per_m2 * total_floor_area

primary_energy_factor_electricity = 1.1  # Example factor
primary_energy_appliances = appliances_energy_use * primary_energy_factor_electricity
primary_energy_cooking = cooking_energy_use * primary_energy_factor_electricity * 365  # Annualize cooking energy

total_primary_energy_use = primary_energy_regulated + primary_energy_appliances
