"""
ireland_3node_stochastic.jl
3-Node Irish Power System (West_NW_Wind, Midlands_Storage, Dublin_East)
Verified against SpineOpt v1.2.0 (entity-flow schema) & backward-compatible with v0.8-v0.10.

Demonstrates:
  1. Programmatic EAV Spine DB creation via SpineOpt.template() + import_data()
  2. 2-Stage Stochastic Weather Tree (Normal Winter, 4-Day Dunkelflaute, High-Wind Storm)
  3. Flexible Multi-Resolution Temporal Blocks (1h elec/BESS vs. 4h LDES/Gas vs. 1d Investment)
  4. Policy trade-offs: West curtailment vs. East offshore, 2h BESS vs. 48h LDES, Gas backup
"""

using SpineOpt
using SpineInterface
using Dates
using JuMP
using Printf

# -------------------------------------------------------------------------
# 1. Helper Utilities: Class-Scoped Schema Detection for SpineOpt v1.2.0
# -------------------------------------------------------------------------
workdir = pwd()
in_path  = joinpath(workdir, "ireland_3node_input.sqlite")
out_path = joinpath(workdir, "ireland_3node_output.sqlite")
rm(in_path; force=true)
rm(out_path; force=true)

input_url  = "sqlite:///" * replace(in_path, "\\" => "/")
output_url = "sqlite:///" * replace(out_path, "\\" => "/")

tpl = SpineOpt.template()
SpineOpt.import_data(input_url, tpl, "Initialise SpineOpt template")

const IS_ENTITY_SCHEMA = haskey(tpl, "entity_classes")

function collect_tpl_schema(tpl)
    classes      = Set{String}()
    class_params = Dict{String, Set{String}}()
    pvls         = Dict{String, Vector{String}}()
    outputs      = Set{String}()

    add_cp!(cls, par) = push!(get!(class_params, cls, Set{String}()), par)

    if IS_ENTITY_SCHEMA
        for c in get(tpl, "entity_classes", [])
            push!(classes, string(c[1]))
        end
        for p in get(tpl, "parameter_definitions", [])
            add_cp!(string(p[1]), string(p[2]))
        end
        for e in get(tpl, "entities", [])
            string(e[1]) == "output" && push!(outputs, string(e[2]))
        end
    else
        for c in get(tpl, "object_classes", [])
            push!(classes, string(c[1]))
        end
        for c in get(tpl, "relationship_classes", [])
            push!(classes, string(c[1]))
        end
        for p in get(tpl, "object_parameters", [])
            add_cp!(string(p[1]), string(p[2]))
        end
        for p in get(tpl, "relationship_parameters", [])
            add_cp!(string(p[1]), string(p[2]))
        end
        for o in get(tpl, "objects", [])
            string(o[1]) == "output" && push!(outputs, string(o[2]))
        end
    end

    for pvl in get(tpl, "parameter_value_lists", [])
        lname = string(pvl[1])
        vals  = pvl[2] isa AbstractVector ? string.(pvl[2]) : [string(pvl[2])]
        append!(get!(pvls, lname, String[]), vals)
    end
    return classes, class_params, pvls, outputs
end

classes, class_params, pvls, valid_outputs = collect_tpl_schema(tpl)

function pick_class(cands::Vector{String})
    for c in cands
        c in classes && return c
    end
    error("None of candidate classes $cands found in SpineOpt template.")
end

function pick_param(cls::String, cands::Vector{String})
    cset = get(class_params, cls, Set{String}())
    for p in cands
        p in cset && return p
    end
    error("None of parameter candidates $cands found on class '$cls'.\nAvailable: $(sort(collect(cset)))")
end

function find_class_param(cls_cands::Vector{String}, par_cands::Vector{String})
    for cls in cls_cands
        cls in classes || continue
        cset = get(class_params, cls, Set{String}())
        for p in par_cands
            p in cset && return (cls, p)
        end
    end
    error("Could not find any of $par_cands across classes $cls_cands.")
end

function pick_pvl(list_cands::Vector{String}, val_cands::Vector{String})
    for lname in list_cands
        haskey(pvls, lname) || continue
        for v in val_cands
            v in pvls[lname] && return v
        end
    end
    return first(val_cands)
end

function to_db_val(x)
    x isa Union{Real, Bool, AbstractString} && return x
    try
        u = SpineInterface.unparse_db_value(x)
        if u isa AbstractDict && haskey(u, "type")
            return u
        end
    catch
    end
    if x isa DateTime
        return Dict("type" => "date_time", "data" => Dates.format(x, "yyyy-mm-ddTHH:MM:SS"))
    elseif x isa Hour
        return Dict("type" => "duration", "data" => "$(Dates.value(x))h")
    elseif x isa Day
        return Dict("type" => "duration", "data" => "$(Dates.value(x))D")
    elseif x isa TimeSeries
        return Dict(
            "type"  => "time_series",
            "data"  => Dict(Dates.format(t, "yyyy-mm-ddTHH:MM:SS") => v for (t, v) in zip(x.indexes, x.values)),
            "index" => Dict("ignore_year" => x.ignore_year, "repeat" => x.repeat),
        )
    elseif x isa Map
        return Dict(
            "type"       => "map",
            "index_type" => "str",
            "data"       => Dict(string(k) => to_db_val(v) for (k, v) in zip(x.indexes, x.values)),
        )
    end
    return x
end

const IS_V1_FLOW = "node__to_unit" in classes
println("Detected SpineOpt schema: ", IS_V1_FLOW ? "v1.x (entity-flow)" : "v0.8-v0.10 (classic)")

C_U_FROM   = pick_class(["node__to_unit", "unit__from_node"])
C_U_TO     = "unit__to_node"
C_U_EFF    = pick_class(["unit_flow__unit_flow", "unit__node__node"])
P_U_EFF    = pick_param(C_U_EFF, ["flow_ratio_equality_coefficient", "fix_ratio_out_in_unit_flow"])
P_U_CAP    = pick_param(C_U_TO,  ["capacity_per_unit", "unit_capacity", "capacity"])
P_U_VOM    = pick_param(C_U_TO,  ["vom_cost", "variable_om_cost"])

C_C_FROM   = pick_class(["node__to_connection", "connection__from_node"])
C_C_TO     = "connection__to_node"
C_C_EFF    = pick_class(["connection_flow__connection_flow", "connection__node__node"])
P_C_EFF    = pick_param(C_C_EFF, ["flow_ratio_equality_coefficient", "fix_ratio_out_in_connection_flow"])
C_C_CAP_CLS, P_C_CAP = find_class_param([C_C_TO, "connection"], ["capacity_per_connection", "connection_capacity", "capacity"])
HAS_EX_CONN = "existing_connections" in get(class_params, "connection", Set{String}())

P_N_DEM    = pick_param("node", ["demand"])
P_N_BAL    = pick_param("node", ["balance_type", "node_balance_type"])
P_N_SLK    = pick_param("node", ["balance_penalty", "node_slack_penalty"])
P_S_HAS    = pick_param("node", ["storage_active", "has_state"])
P_S_CAP    = pick_param("node", ["storage_state_max", "node_state_cap"])
P_S_LOSS   = pick_param("node", ["storage_self_discharge", "frac_state_loss"])
P_S_COEFF  = pick_param("node", ["storage_state_coefficient", "state_coeff"])
P_S_INIT   = pick_param("node", ["storage_state_initial", "initial_node_state"])

P_U_NUM    = pick_param("unit", ["existing_units", "number_of_units"])
P_U_AF     = pick_param("unit", ["availability_factor", "unit_availability_factor"])
P_U_CAND   = pick_param("unit", ["investment_count_max_cumulative", "candidate_units"])
P_U_IC     = pick_param("unit", ["unit_investment_cost", "investment_cost"])
P_U_IVT    = pick_param("unit", ["investment_variable_type", "unit_investment_variable_type"])

P_S_NUM    = pick_param("node", ["existing_storages", "number_of_storages"])
P_S_CAND   = pick_param("node", ["storage_investment_count_max_cumulative", "candidate_storages"])
P_S_IC     = pick_param("node", ["storage_investment_cost", "investment_cost"])
P_S_IVT    = pick_param("node", ["storage_investment_variable_type", "investment_variable_type"])
P_U_FIXNEW = pick_param("unit", ["investment_count_fix_new"])
P_S_FIXNEW = pick_param("node", ["storage_investment_count_fix_new"])

# Allow free investment on Day 1 (Stage1_Root omitted), lock new builds to 0 in Stage 2
# Unfixed on Day 1 (before 2030-01-08), fixed to 0.0 new builds in Stage 2 (Days 2-7)
ts_fix_zero_stage2 = TimeSeries(
    [DateTime("2030-01-08T00:00:00"), DateTime("2030-01-14T00:00:00")],
    [0.0, 0.0],
    false,
    false
)

V_BAL_NONE = pick_pvl(["balance_type_list", "node_balance_type_list"], ["none", "balance_type_none"])
V_MOD_STD  = pick_pvl(["model_type_list"], ["spineopt_standard"])
V_INV_CONT = pick_pvl(["variable_type_list", "investment_variable_type_list"], ["continuous", "variable_type_continuous"])

u_from_tuple(u, n) = (C_U_FROM == "node__to_unit") ? [n, u] : [u, n]
c_from_tuple(c, n) = (C_C_FROM == "node__to_connection") ? [n, c] : [c, n]
u_eff_tuple(u, n_out, n_in) = (C_U_EFF == "unit_flow__unit_flow") ? [u, n_out, n_in, u] : [u, n_out, n_in]
c_eff_tuple(c, n_out, n_in) = (C_C_EFF == "connection_flow__connection_flow") ? [c, n_out, n_in, c] : [c, n_out, n_in]

# -------------------------------------------------------------------------
# 2. Synthetic Irish Winter Week Data (168 Hours: Mon 7 Jan - Mon 14 Jan 2030)
# -------------------------------------------------------------------------
t_start = DateTime("2030-01-07T00:00:00")
t_end   = DateTime("2030-01-14T00:00:00")

timestamps = collect(t_start:Hour(1):t_end)
n_t = length(timestamps)

diurnal = [begin
    h = hour(t)
    if 17 <= h <= 20
        1.20
    elseif 8 <= h <= 16
        1.05
    elseif 0 <= h <= 5
        0.78
    else
        0.92
    end
end for t in timestamps]

demand_dublin_norm = 2800.0 .* diurnal
demand_dublin_dunk = 3080.0 .* diurnal # Cold Dunkelflaute increases peak demand +10%
demand_west        = fill(300.0, n_t)
demand_midlands    = fill(150.0, n_t)

pv_norm = [max(0.0, 0.22 * sin(pi * (hour(t) - 8) / 8)) * (8 <= hour(t) <= 16 ? 1.0 : 0.0) for t in timestamps]
pv_dunk = 0.25 .* pv_norm

af_west_norm   = Vector{Float64}(undef, n_t)
af_west_dunk   = Vector{Float64}(undef, n_t)
af_west_storm  = Vector{Float64}(undef, n_t)
af_east_norm   = Vector{Float64}(undef, n_t)
af_east_dunk   = Vector{Float64}(undef, n_t)
af_east_storm  = Vector{Float64}(undef, n_t)

for (i, t) in enumerate(timestamps)
    hr = i - 1
    if hr < 24
        # Stage 1 (Day 1): Windy start allowing Day-1 storage pre-charging
        af_west_norm[i] = af_west_dunk[i] = af_west_storm[i] = 0.80
        af_east_norm[i] = af_east_dunk[i] = af_east_storm[i] = 0.72
    else
        af_west_norm[i]  = 0.50 + 0.12 * sin(2pi * hr / 36)
        af_east_norm[i]  = 0.56 + 0.10 * sin(2pi * hr / 36 + 0.4)
        af_west_dunk[i]  = (24 <= hr < 120) ? 0.03 : 0.48
        af_east_dunk[i]  = (24 <= hr < 120) ? 0.06 : 0.55
        af_west_storm[i] = (24 <= hr < 120) ? 0.94 : 0.65
        af_east_storm[i] = (24 <= hr < 120) ? 0.88 : 0.60
    end
end

ts(vals) = TimeSeries(timestamps, vals, false, false)

map_west_af = Map(
    ["Stage1_Root", "Normal_Winter", "Severe_Dunkelflaute", "High_Wind_Curtailment"],
    [ts(af_west_norm), ts(af_west_norm), ts(af_west_dunk), ts(af_west_storm)]
)
map_east_af = Map(
    ["Stage1_Root", "Normal_Winter", "Severe_Dunkelflaute", "High_Wind_Curtailment"],
    [ts(af_east_norm), ts(af_east_norm), ts(af_east_dunk), ts(af_east_storm)]
)
map_pv_af = Map(
    ["Stage1_Root", "Normal_Winter", "Severe_Dunkelflaute", "High_Wind_Curtailment"],
    [ts(pv_norm), ts(pv_norm), ts(pv_dunk), ts(pv_norm)]
)
map_dublin_demand = Map(
    ["Stage1_Root", "Normal_Winter", "Severe_Dunkelflaute", "High_Wind_Curtailment"],
    [ts(demand_dublin_norm), ts(demand_dublin_norm), ts(demand_dublin_dunk), ts(demand_dublin_norm)]
)

# -------------------------------------------------------------------------
# 3. Build Spine Entity-Attribute-Value Dictionary & Import into SQLite
# -------------------------------------------------------------------------
entities_list = Any[]
pvals_list    = Any[]

add_ent!(cls, name) = push!(entities_list, [cls, name])
add_par!(cls, name, param, val; alt="Base") = push!(pvals_list, [cls, name, param, to_db_val(val), alt])

# 3a. Model, Temporal Blocks & Reporting
add_ent!("model", "Ireland_3Node")
add_par!("model", "Ireland_3Node", "model_type", V_MOD_STD)
add_par!("model", "Ireland_3Node", "model_start", t_start)
add_par!("model", "Ireland_3Node", "model_end", t_end)

for (tb, res) in [("tb_1h", Hour(1)), ("tb_4h", Hour(4)), ("tb_inv", Day(1))]
    add_ent!("temporal_block", tb)
    add_par!("temporal_block", tb, "resolution", res)
    add_ent!("model__temporal_block", ["Ireland_3Node", tb])
end
add_ent!("model__default_temporal_block", ["Ireland_3Node", "tb_1h"])
add_ent!("model__default_investment_temporal_block", ["Ireland_3Node", "tb_inv"])

add_ent!("report", "report1")
add_ent!("model__report", ["Ireland_3Node", "report1"])
for out_var in [
    "unit_flow", "connection_flow", "node_state", "node_slack_pos",
    "units_invested_available", "storages_invested_available", "total_costs"
]
    if isempty(valid_outputs) || (out_var in valid_outputs)
        add_ent!("report__output", ["report1", out_var])
    end
end

# 3b. Two-Stage Stochastic Structure (shared across operations & investments)
for sc in ["Stage1_Root", "Normal_Winter", "Severe_Dunkelflaute", "High_Wind_Curtailment"]
    add_ent!("stochastic_scenario", sc)
end
for (p, c) in [
    ("Stage1_Root", "Normal_Winter"),
    ("Stage1_Root", "Severe_Dunkelflaute"),
    ("Stage1_Root", "High_Wind_Curtailment"),
]
    add_ent!("parent_stochastic_scenario__child_stochastic_scenario", [p, c])
end

add_ent!("stochastic_structure", "weather_tree")
add_ent!("model__stochastic_structure", ["Ireland_3Node", "weather_tree"])
add_ent!("model__default_stochastic_structure", ["Ireland_3Node", "weather_tree"])
add_ent!("model__default_investment_stochastic_structure", ["Ireland_3Node", "weather_tree"])

add_ent!("stochastic_structure__stochastic_scenario", ["weather_tree", "Stage1_Root"])
add_par!("stochastic_structure__stochastic_scenario", ["weather_tree", "Stage1_Root"], "weight_relative_to_parents", 1.0)
add_par!("stochastic_structure__stochastic_scenario", ["weather_tree", "Stage1_Root"], "stochastic_scenario_end", Hour(24))

for (sc, w) in [("Normal_Winter", 0.50), ("Severe_Dunkelflaute", 0.25), ("High_Wind_Curtailment", 0.25)]
    add_ent!("stochastic_structure__stochastic_scenario", ["weather_tree", sc])
    add_par!("stochastic_structure__stochastic_scenario", ["weather_tree", sc], "weight_relative_to_parents", w)
end

# 3c. Nodes
for n in ["West_NW_Wind", "Midlands_Storage", "Dublin_East"]
    add_ent!("node", n)
    add_par!("node", n, P_N_SLK, 10_000.0)
end
add_par!("node", "West_NW_Wind",     P_N_DEM, ts(demand_west))
add_par!("node", "Midlands_Storage", P_N_DEM, ts(demand_midlands))
add_par!("node", "Dublin_East",      P_N_DEM, map_dublin_demand)

# Infinite fuel source (no nodal balance)
add_ent!("node", "Gas_Fuel")
add_par!("node", "Gas_Fuel", P_N_BAL, V_BAL_NONE)
add_ent!("node__temporal_block", ["Gas_Fuel", "tb_4h"]) # Multi-resolution demo

# Balanced node (default balance_type) so imports via Celtic_Interconnector
# must come from France_Import_Supply at €110/MWh
add_ent!("node", "France_Grid")

# Storage Nodes: 2-hour BESS (1h resolution) vs. 48-hour LDES (4h resolution)
add_ent!("node", "BESS_2h_Tank")
add_par!("node", "BESS_2h_Tank", P_S_HAS,    true)
add_par!("node", "BESS_2h_Tank", P_S_CAP,    1.0)     # 1 MWh per storage unit
add_par!("node", "BESS_2h_Tank", P_S_NUM,    0.0)
add_par!("node", "BESS_2h_Tank", P_S_CAND,   1_000.0) # Max 1,000 MWh (2h x 500 MW)
add_par!("node", "BESS_2h_Tank", P_S_IVT,    V_INV_CONT)
add_par!("node", "BESS_2h_Tank", P_S_IC,     160.0)   # €/MWh-week (expensive energy capacity)
add_par!("node", "BESS_2h_Tank", P_S_FIXNEW, ts_fix_zero_stage2)
add_par!("node", "BESS_2h_Tank", P_S_LOSS,   0.001)
add_par!("node", "BESS_2h_Tank", P_S_COEFF,  1.0)
add_par!("node", "BESS_2h_Tank", P_S_INIT,   0.0)

add_ent!("node", "LDES_Reservoir")
add_ent!("node__temporal_block", ["LDES_Reservoir", "tb_4h"]) # Multi-resolution 4h LDES state
add_par!("node", "LDES_Reservoir", P_S_HAS,    true)
add_par!("node", "LDES_Reservoir", P_S_CAP,    1.0)      # 1 MWh per storage unit
add_par!("node", "LDES_Reservoir", P_S_NUM,    0.0)
add_par!("node", "LDES_Reservoir", P_S_CAND,   24_000.0) # Max 24,000 MWh (48h x 500 MW)
add_par!("node", "LDES_Reservoir", P_S_IVT,    V_INV_CONT)
add_par!("node", "LDES_Reservoir", P_S_IC,     15.0)     # €/MWh-week (cheap cavern/hydro energy volume)
add_par!("node", "LDES_Reservoir", P_S_FIXNEW, ts_fix_zero_stage2)
add_par!("node", "LDES_Reservoir", P_S_LOSS,   0.0002)
add_par!("node", "LDES_Reservoir", P_S_COEFF,  1.0)
add_par!("node", "LDES_Reservoir", P_S_INIT,   0.0)

# 3d. Transmission Connections
function set_conn_cap!(cname, n_to, cap_mw)
    if C_C_CAP_CLS == "connection"
        add_par!("connection", cname, P_C_CAP, cap_mw)
    else
        add_par!(C_C_CAP_CLS, [cname, n_to], P_C_CAP, cap_mw)
    end
end

function add_bidirectional_line!(cname, n_a, n_b, cap_mw; loss=0.01)
    add_ent!("connection", cname)
    HAS_EX_CONN && add_par!("connection", cname, "existing_connections", 1.0)
    add_ent!(C_C_FROM, c_from_tuple(cname, n_a))
    add_ent!(C_C_TO,   [cname, n_b])
    add_ent!(C_C_FROM, c_from_tuple(cname, n_b))
    add_ent!(C_C_TO,   [cname, n_a])

    set_conn_cap!(cname, n_b, cap_mw)
    if C_C_CAP_CLS != "connection"
        set_conn_cap!(cname, n_a, cap_mw)
    end

    add_ent!(C_C_EFF, c_eff_tuple(cname, n_b, n_a))
    add_ent!(C_C_EFF, c_eff_tuple(cname, n_a, n_b))
    add_par!(C_C_EFF, c_eff_tuple(cname, n_b, n_a), P_C_EFF, 1.0 - loss)
    add_par!(C_C_EFF, c_eff_tuple(cname, n_a, n_b), P_C_EFF, 1.0 - loss)
end

add_bidirectional_line!("Line_West_Midlands",   "West_NW_Wind",     "Midlands_Storage", 1_400.0)
add_bidirectional_line!("Line_Midlands_Dublin", "Midlands_Storage", "Dublin_East",      1_600.0)

add_ent!("connection", "Celtic_Interconnector")
HAS_EX_CONN && add_par!("connection", "Celtic_Interconnector", "existing_connections", 1.0)
add_ent!(C_C_FROM, c_from_tuple("Celtic_Interconnector", "France_Grid"))
add_ent!(C_C_TO,   ["Celtic_Interconnector", "Dublin_East"])
set_conn_cap!("Celtic_Interconnector", "Dublin_East", 700.0)
add_ent!(C_C_EFF,  c_eff_tuple("Celtic_Interconnector", "Dublin_East", "France_Grid"))
add_par!(C_C_EFF,  c_eff_tuple("Celtic_Interconnector", "Dublin_East", "France_Grid"), P_C_EFF, 0.97)

# 3e. Generation, Import & Storage Converter Units
const CUMULATIVE_MAX = (P_U_CAND == "investment_count_max_cumulative")

function add_vre_unit!(uname, target_node, existing_mw, max_new_mw, inv_cost_wk, af_map)
    add_ent!("unit", uname)
    add_ent!(C_U_TO, [uname, target_node])
    add_par!(C_U_TO, [uname, target_node], P_U_CAP, 1.0)
    add_par!(C_U_TO, [uname, target_node], P_U_VOM, 0.5)
    add_par!("unit", uname, P_U_NUM, existing_mw)
    add_par!("unit", uname, P_U_AF,  af_map)
    if max_new_mw > 0
        cand_bound = CUMULATIVE_MAX ? (existing_mw + max_new_mw) : max_new_mw
        add_par!("unit", uname, P_U_CAND,   cand_bound)
        add_par!("unit", uname, P_U_IVT,    V_INV_CONT)
        add_par!("unit", uname, P_U_IC,     inv_cost_wk)
        add_par!("unit", uname, P_U_FIXNEW, ts_fix_zero_stage2)
    end
end

add_vre_unit!("West_Onshore_Wind",    "West_NW_Wind", 1_500.0, 1_500.0, 1_800.0, map_west_af)
add_vre_unit!("Dublin_Offshore_East", "Dublin_East",    400.0, 1_200.0, 3_000.0, map_east_af)
add_vre_unit!("Dublin_Solar_PV",      "Dublin_East",    600.0,     0.0,     0.0, map_pv_af)

function add_thermal_unit!(uname, fuel_node, elec_node, cap_mw, eff, fuel_carbon_cost_th)
    add_ent!("unit", uname)
    add_par!("unit", uname, P_U_NUM, 1.0)
    add_ent!(C_U_FROM, u_from_tuple(uname, fuel_node))
    add_ent!(C_U_TO,   [uname, elec_node])
    add_ent!(C_U_EFF,  u_eff_tuple(uname, elec_node, fuel_node))
    add_par!(C_U_TO,   [uname, elec_node], P_U_CAP, cap_mw)
    add_par!(C_U_FROM, u_from_tuple(uname, fuel_node), P_U_VOM, fuel_carbon_cost_th)
    add_par!(C_U_EFF,  u_eff_tuple(uname, elec_node, fuel_node), P_U_EFF, eff)
end

# 2030/2035 high gas + ETS carbon cost (€115/MWh_th -> ~€209/MWh_e CCGT, ~€303/MWh_e OCGT)
add_thermal_unit!("Dublin_Gas_CCGT", "Gas_Fuel", "Dublin_East", 2_800.0, 0.55, 115.0)
add_thermal_unit!("Dublin_Gas_OCGT", "Gas_Fuel", "Dublin_East",   800.0, 0.38, 115.0)

add_ent!("unit", "France_Import_Supply")
add_par!("unit", "France_Import_Supply", P_U_NUM, 1.0)
add_ent!(C_U_TO, ["France_Import_Supply", "France_Grid"])
add_par!(C_U_TO, ["France_Import_Supply", "France_Grid"], P_U_CAP, 700.0)
add_par!(C_U_TO, ["France_Import_Supply", "France_Grid"], P_U_VOM, 110.0)

function add_storage_converters!(prefix, bus_node, tank_node, max_power_mw, inv_cost_mw_wk, eff_one_way)
    chg, dis = "$(prefix)_Charge", "$(prefix)_Discharge"
    for (u, n_in, n_out) in [(chg, bus_node, tank_node), (dis, tank_node, bus_node)]
        add_ent!("unit", u)
        add_ent!(C_U_FROM, u_from_tuple(u, n_in))
        add_ent!(C_U_TO,   [u, n_out])
        add_ent!(C_U_EFF,  u_eff_tuple(u, n_out, n_in))
        add_par!(C_U_TO,   [u, n_out], P_U_CAP, 1.0)
        add_par!(C_U_EFF,  u_eff_tuple(u, n_out, n_in), P_U_EFF, eff_one_way)
        add_par!("unit", u, P_U_NUM,    0.0)
        add_par!("unit", u, P_U_CAND,   max_power_mw)
        add_par!("unit", u, P_U_IVT,    V_INV_CONT)
        add_par!("unit", u, P_U_IC,     u == chg ? inv_cost_mw_wk : 0.0)
        add_par!("unit", u, P_U_FIXNEW, ts_fix_zero_stage2)
    end
end

add_storage_converters!("BESS_2h", "Midlands_Storage", "BESS_2h_Tank",   500.0, 300.0, sqrt(0.88))
add_storage_converters!("LDES",    "Midlands_Storage", "LDES_Reservoir", 500.0, 450.0, sqrt(0.75))

data_dict = IS_ENTITY_SCHEMA ? Dict(
    "alternatives"     => [["Base"]],
    "entities"         => entities_list,
    "parameter_values" => pvals_list,
) : Dict(
    "alternatives" => [["Base"]],
    "objects"      => [e for e in entities_list if !(e[2] isa AbstractVector)],
    "relationships"=> [e for e in entities_list if  (e[2] isa AbstractVector)],
    "object_parameter_values"       => [p for p in pvals_list if !(p[2] isa AbstractVector)],
    "relationship_parameter_values" => [p for p in pvals_list if  (p[2] isa AbstractVector)],
)

SpineInterface.import_data(input_url, data_dict, "Populate 3-node Irish stochastic test system")
println("Populated input database: ", in_path)

# -------------------------------------------------------------------------
# 4. Solve Two-Stage Stochastic Model with SpineOpt
# -------------------------------------------------------------------------
println("\nRunning SpineOpt (2-Stage Stochastic LP/MILP)...")
m = run_spineopt(input_url, output_url; upgrade=true, log_level=1)
println("\nSolve status: ", JuMP.termination_status(m))
@printf("Expected Total System Cost (Stage 1 + Expected Stage 2): €%.2f Million\n", JuMP.objective_value(m) / 1e6)

# -------------------------------------------------------------------------
# 5. Extract & Print Key Policy Metrics in an Isolated Output Module
# -------------------------------------------------------------------------
out_mod = Module(:SpineOutput)
Core.eval(out_mod, :(using SpineInterface))
Base.invokelatest(using_spinedb, output_url, out_mod)

last_val(val) = val isa TimeSeries ? val.values[end] : Float64(val)
has_out(sym)  = isdefined(out_mod, sym)
get_out(sym)  = getproperty(out_mod, sym)

println("\n=== 1. Stage-1 Optimal Investments (Here-and-Now Decisions) ===")
existing_mw = Dict(
    "West_Onshore_Wind"    => 1_500.0,
    "Dublin_Offshore_East" =>   400.0,
    "BESS_2h_Charge"       =>     0.0,
    "LDES_Charge"          =>     0.0,
)
west_invested = 0.0

if has_out(:units_invested_available)
    p_uinv = get_out(:units_invested_available)
    for idx in Base.invokelatest(indices, p_uinv)
        u_name = string(idx.unit.name)
        if haskey(existing_mw, u_name) && idx.stochastic_scenario.name == :Stage1_Root
            inv_mw = last_val(Base.invokelatest(p_uinv; idx...))
            tot_mw = existing_mw[u_name] + inv_mw
            if u_name == "West_Onshore_Wind"
                global west_invested = inv_mw
            end
            @printf("  %-24s : %8.1f MW newly invested (%8.1f MW total)\n", u_name, inv_mw, tot_mw)
        end
    end
end

if has_out(:storages_invested_available)
    p_sinv = get_out(:storages_invested_available)
    for idx in Base.invokelatest(indices, p_sinv)
        n_name = string(idx.node.name)
        if idx.stochastic_scenario.name == :Stage1_Root
            val = last_val(Base.invokelatest(p_sinv; idx...))
            @printf("  %-24s : %8.1f MWh energy capacity\n", n_name, val)
        end
    end
end

function get_unit_gen_mwh(unit_sym::Symbol, node_sym::Symbol, scen_sym::Symbol)
    has_out(:unit_flow) || return 0.0
    p_uf = get_out(:unit_flow)
    total = 0.0
    for idx in Base.invokelatest(indices, p_uf)
        dir_ok = hasproperty(idx, :direction) ? (idx.direction.name == :to_node) : true
        if idx.unit.name == unit_sym && idx.node.name == node_sym &&
           dir_ok && idx.stochastic_scenario.name == scen_sym
            v = Base.invokelatest(p_uf; idx...)
            total += v isa TimeSeries ? sum(v.values) : Float64(v)
        end
    end
    return total
end

println("\n=== 2. Stage-2 Operational Outcomes by Weather Realisation (Days 2-7) ===")
west_cap_total = 1_500.0 + west_invested

branches = [
    (:Normal_Winter,         af_west_norm[25:end-1],  demand_dublin_norm[25:end-1]),
    (:Severe_Dunkelflaute,   af_west_dunk[25:end-1],  demand_dublin_dunk[25:end-1]),
    (:High_Wind_Curtailment, af_west_storm[25:end-1], demand_dublin_norm[25:end-1]),
]

for (sc, af_stage2, dem_dub) in branches
    west_avail_mwh = sum(af_stage2) * west_cap_total
    west_gen_mwh   = get_unit_gen_mwh(:West_Onshore_Wind, :West_NW_Wind, sc)
    curtail_mwh    = max(0.0, west_avail_mwh - west_gen_mwh)
    curtail_pct    = 100.0 * curtail_mwh / max(west_avail_mwh, 1.0)

    east_gen_mwh   = get_unit_gen_mwh(:Dublin_Offshore_East, :Dublin_East, sc)
    celtic_mwh     = get_unit_gen_mwh(:France_Import_Supply, :France_Grid, sc)
    gas_mwh        = get_unit_gen_mwh(:Dublin_Gas_CCGT, :Dublin_East, sc) +
                     get_unit_gen_mwh(:Dublin_Gas_OCGT, :Dublin_East, sc)
    tot_dem        = sum(dem_dub) + 144 * (300.0 + 150.0)
    gas_pct        = 100.0 * gas_mwh / tot_dem

    ldes_dis       = get_unit_gen_mwh(:LDES_Discharge, :Midlands_Storage, sc)
    bess_dis       = get_unit_gen_mwh(:BESS_2h_Discharge, :Midlands_Storage, sc)

    @printf("\nBranch: %-22s\n", string(sc))
    @printf("  West Wind Available / Dispatched : %8.0f / %8.0f MWh\n", west_avail_mwh, west_gen_mwh)
    @printf("  West Wind Curtailed (Bottleneck) : %8.0f MWh (%.1f%%)\n", curtail_mwh, curtail_pct)
    @printf("  East Offshore / Celtic Imports   : %8.0f / %8.0f MWh\n", east_gen_mwh, celtic_mwh)
    @printf("  Gas Backup Generation            : %8.0f MWh (%.1f%% of demand)\n", gas_mwh, gas_pct)
    @printf("  Storage Discharged (BESS / LDES) : %8.0f / %8.0f MWh\n", bess_dis, ldes_dis)
end

println("\n=== 3. Storage State-of-Charge (SOC) at Day 1 Pre-Charge vs. Stage 2 ===")
if has_out(:node_state)
    p_ns = get_out(:node_state)
    for idx in Base.invokelatest(indices, p_ns)
        n_name  = idx.node.name
        sc_name = idx.stochastic_scenario.name
        if n_name in (:BESS_2h_Tank, :LDES_Reservoir) &&
           sc_name in (:Stage1_Root, :Normal_Winter, :Severe_Dunkelflaute, :High_Wind_Curtailment)
            v = Base.invokelatest(p_ns; idx...)
            vals = v isa TimeSeries ? v.values : [Float64(v)]
            @printf("  %-15s | %-22s | Start: %7.1f MWh | Max: %7.1f MWh | Min: %7.1f MWh\n",
                    string(n_name), string(sc_name), vals[1], maximum(vals), minimum(vals))
        end
    end
end