"""
Portugal's 1,050 MVA grid-storage tenders: battery sizing pre-screen
====================================================================

**News (9 November 2026):** Portugal offered 750 MVA of standalone BESS grid
access and 300 MVA of renewable-plus-BESS grid access, with applications
reported due 22 December 2026. MVA is apparent-power access, **not** installed
battery MW, actual dispatch or MWh generation.

**Business question:** What conditional inverter power and nameplate storage
energy would be required for candidate bids, including end-of-life allowance?

**Evidence:** Portuguese DGEG tender orders 12924-B/2026 and 12924-C/2026,
government announcement (27 October), and pv magazine España (9 November).
The source-level :download:`evidence record <portugal_storage_auction_2026.json>`
separates dated reported facts from illustrative engineering assumptions.
See :doc:`technical guide </_generated/guides/portugal-storage-auction>`.

**Not legal compliance:** DGEG's co-located wording refers to four hours
at *maximum injection power*. The battery-rated-power calculation below is
a preliminary 20%-inverter stress only, compared against a stricter full
injection stress. Neither substitutes for the controlling tender documents.
"""

# %%
# 1. Audit external evidence and keep modeled inputs separate from facts.
import json
from pathlib import Path

import matplotlib.pyplot as plt

from energy_methods.portugal_storage_auction import (
    AUCTION_CAPACITY_MVA,
    MINIMUM_BID_MVA,
    StorageAuctionScenario,
    screen_portugal_storage_auction,
)

script_path = Path(globals().get("__file__", Path.cwd() / "plot_portugal_storage_auction_2026.py"))
evidence = json.loads(
    (script_path.resolve().parent / "portugal_storage_auction_2026.json").read_text(
        encoding="utf-8"
    )
)
sources = {row["source_id"]: row for row in evidence["reported_evidence"]}
assumed = evidence["illustrative_assumptions_NOT_OBSERVED"]
assert sources["dgeg_standalone"]["capacity_mva"] == AUCTION_CAPACITY_MVA["standalone"]
assert sources["dgeg_colocated"]["capacity_mva"] == AUCTION_CAPACITY_MVA["colocated"]
assert sources["pv_magazine_nov9"]["minimum_bid_mva"] == MINIMUM_BID_MVA
print("Official offered connection pools: 750 MVA standalone + 300 MVA co-located")
print("SCENARIO values below are not observed Portuguese battery installations.")

# %%
# 2. Size nameplate sensitivity for hypothetical MVA candidates.
bid_mva = assumed["bid_mva"]
categories = ("standalone", "colocated")
screened = {
    category: [
        screen_portugal_storage_auction(
            StorageAuctionScenario(
                category,
                value,
                ac_discharge_efficiency=assumed["ac_discharge_efficiency"],
                end_of_life_usable_fraction=assumed["end_of_life_usable_fraction"],
            )
        )
        for value in bid_mva
    ]
    for category in categories
}
for category, results in screened.items():
    for result in results:
        print(
            f"{category:10} {result.awarded_capacity_mva:.0f} MVA: "
            f"{result.minimum_bess_ac_mw:.0f} MW inverter screen, "
            f"{result.minimum_nameplate_mwh:.1f} MWh assumed nominal, "
            f"{result.full_export_four_hour_nameplate_mwh:.1f} MWh full-export stress"
        )
fig, ax = plt.subplots(figsize=(8.8, 4.6), layout="constrained")
for category, results in screened.items():
    ax.plot(
        bid_mva,
        [result.minimum_nameplate_mwh for result in results],
        marker="o",
        label=f"{category}: 4 h at BESS power",
    )
ax.plot(
    bid_mva,
    [result.full_export_four_hour_nameplate_mwh for result in screened["colocated"]],
    linestyle="--",
    color="black",
    label="co-located: 4 h full-injection stress",
)
ax.set(
    xlabel="Candidate injection access (MVA; NOT MW)",
    ylabel="Illustrative nominal battery energy (MWh)",
    title="Portugal tenders: separate four-hour design interpretations",
)
ax.legend()
plt.show()

# %%
# 3. Unit and loss sensitivity: MVA cannot silently be treated as MW.
pfs = assumed["active_power_factor"]
fig, ax = plt.subplots(figsize=(8.8, 4.6), layout="constrained")
for category in categories:
    answers = [
        screen_portugal_storage_auction(
            StorageAuctionScenario(
                category,
                50,
                active_power_factor=pf,
                ac_discharge_efficiency=assumed["ac_discharge_efficiency"],
                end_of_life_usable_fraction=assumed["end_of_life_usable_fraction"],
            )
        )
        for pf in pfs
    ]
    ax.plot(
        pfs,
        [result.minimum_nameplate_mwh for result in answers],
        marker="o",
        label=f"{category} screen",
    )
ax.set(
    xlabel="Assumed active power factor (MW/MVA)",
    ylabel="Conditional nameplate battery capacity (MWh)",
    title="50 MVA bid: hypothetical power-factor sensitivity",
)
ax.legend()
plt.show()

# %%
# Interpretation: no individual node availability, license eligibility, PPA,
# battery dispatch measurements, market revenues, deposits or costs are known.
# Reproduce: uv run --no-sync python examples/analysis/plot_portugal_storage_auction_2026.py
