Metadata-Version: 2.5
Name: italian-energy
Version: 0.13.9
Summary: Deterministic, domain-first models for comparing Italian electricity offers.
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Office/Business :: Financial
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: defusedxml<1,>=0.7
Requires-Dist: pydantic<3,>=2.10
Requires-Dist: truststore<0.11,>=0.10.4
Provides-Extra: arera
Requires-Dist: openpyxl<4,>=3.1.5; extra == 'arera'
Requires-Dist: pypdf<7,>=5; extra == 'arera'
Provides-Extra: gme
Requires-Dist: pypdf<7,>=5; extra == 'gme'
Description-Content-Type: text/markdown

# italian-energy-core

Libreria Python open source, domain-first e deterministica per modellare, simulare e confrontare offerte di energia elettrica in Italia.

> Core `0.13.9` — discovery tariffaria coerente con la decorrenza e verifica degli atti sul gasolio di ottobre.

Il package installabile è disponibile come wheel e sdist. L'importer Portale
Offerte opera solo su cataloghi open-data ufficiali, replay storici esatti e
offerte elettriche domestiche BT; gas e UI restano fuori scope.

## Obiettivi

Il package `italian_energy` è pensato come core riusabile per backend, comparatori, MCP server, frontend, Home Assistant, notebook e servizi cloud. Il dominio non dipende da Azure, AWS/GCP, web framework, database, autenticazione, LLM o sistemi AI.

La logica economica dovrà essere deterministica, testabile, riproducibile e spiegabile. Un LLM non viene usato per calcolare costi.

## Installazione locale

```bash
uv sync --dev
uv run pytest
```

Installazione del package dalla release pubblicata:

```bash
pip install italian-energy==0.13.9
```

La release `0.13.4` conserva provenienza e semantica delle voci `Dispacciamento`
fino alla bolletta, usa `VALORE_DISP` del codice Portal `99` solo come addebito
separato e blocca i riferimenti senza un importo verificato. Aggiunge inoltre
la copertura esplicita delle perdite e di dispacciamento/capacità sul contratto
corrente, le finestre effettivamente applicate e la motivazione verificata
dell'accisa zero per l'esenzione mensile residente. Mantiene l'esclusione
auditabile di `TIPO_OFFERTA=04` e il fallback GME 0.13.1; il base runtime non
aggiunge dipendenze XLSX. Per le offerte domestiche col codice Portal 14,
acquisisce il CdispD ufficiale dal CSV giornaliero e lo applica alla stima
annuale come assunzione esplicita, mantenendo digest e provenance senza
alterare il replay storico o i tre scenari PUN.

### Novità della 0.13.7

Il confronto riusa le serializzazioni degli input immutabili e della provenance
nella singola richiesta. Le componenti regolatorie lineari mensili vengono
riutilizzate soltanto con tutte le dipendenze invariate, dopo i controlli di
ogni bolletta. Prezzi indicizzati, IVA, accise a soglia, ranking e totali
continuano a essere calcolati per lo scenario corretto. Schemi, capability,
formule, precisione e digest rimangono compatibili (Specs 019/020).

Il replay integrato da 950 offerte, insieme alle ottimizzazioni di
serializzazione della Platform, misura una mediana locale di 57,148 s contro
169,943 s. La sola wheel Core non contiene le modifiche della Platform e
queste misure non garantiscono una latenza massima su altri carichi.

### Novità della 0.13.8

Al cambio mese, se il PDF GME del mese appena concluso è assente e la fonte
ufficiale prova che la pubblicazione è ancora incompleta, il Core può mantenere
il PUN del mese precedente con dodici mesi GME completi, consecutivi e verificati.
Il ritardo ammesso è al massimo un mese; il risultato espone mese atteso,
riferimento effettivo, finestra GME, provenienza e prova del ritardo. Consumi e
data del confronto mantengono il periodo originario. Il confronto resta offline
su input congelati. I nuovi envelope versionati preservano i lettori storici.
La preparazione e i limiti della verifica sono in
[`docs/release-0.13.8-preparation.md`](docs/release-0.13.8-preparation.md).

### Novità della 0.13.6

Il confronto usa l'ultimo mese PUN completo verificato come riferimento sui
dodici mesi stimati, con metodo, periodo e valore esposti. Le tariffe biorarie
BF1/BF23 sono applicabili ai consumi F1/F2/F3 completi senza medie inventate.
La preferenza esplicita `activation_method="ALL"` ricerca su tutti i canali;
`02` mantiene il suo significato originale. I calcoli fissi riusciti sono
riutilizzati nei tre scenari dello stesso confronto, conservando risultati
e digest; gli indicizzati e i risparmi restano specifici dello scenario.
Sono incluse le correzioni degli ID ARERA compatti e della semantica delle
componenti energetiche indicizzate. Le Specs 016/017/018 e l'addendum della
Spec 008 documentano comportamento, limiti e regressioni.

### Novità della 0.13.5

La versione separa la scadenza per aderire dalla durata economica:
un'offerta rimane selezionabile fino al giorno di scadenza incluso, mentre i
prezzi e le quote decorrono dall'attivazione simulata. Le condizioni dichiarate
per dodici mesi coprono così l'intero anno, anche se l'adesione termina prima
dell'attivazione. I metadati `economic_terms` riportano durata, ambito e fonte
per evidenziare condizioni superiori a dodici mesi, senza attribuire un prezzo
bloccato alle offerte indicizzate. Le condizioni indeterminate permettono una
stima annua sui prezzi predefiniti pubblicati, senza una promessa di durata.
Un nuovo refresh del catalogo è necessario per acquisire il parser v6; risultati e snapshot storici restano leggibili senza ricalcolo.

## Architettura

- `domain/`: value object, entità, provenance e risultati immutabili;
- `pricing/`: contratto del Pricing Engine e evaluator fixed/indexed deterministici;
- `billing/`: contratto e Billing Engine regolatorio con riconciliazione esplicita;
- `comparison/`: confronto deterministico all-in su offerte normalizzate, con matrice di copertura obbligatoria;
- `portal_offers/`: acquisizione allowlisted, snapshot/provenance, parsing e normalizzazione dei cataloghi Mercato Libero/PLACET verso il Comparison Engine;
- `recommendation/`: preferenze strutturate, shortlist e decisione consultiva separate dai costi;
- `market/`: indici del catalogo, report GME ufficiali e dati di mercato;
- `arera/`: discovery regolatoria, parser versionati e snapshot raw; il rollover usa l'extra opzionale `arera` (`openpyxl` per i workbook e `pypdf` per il listino ADM); il base non installa queste dipendenze;
- `data/billing/`: ruleset e matrice JSON congelati, caricabili senza dipendenze XLSX.
- `integration/`: manifest, envelope JSON versionati e façade storica, corrente
  e prospettica Core–Platform;

Le spec sono normative. Gli ADR registrano decisioni architetturali. Il Memory Bank descrive lo stato corrente e non sostituisce le spec.

## Sviluppo

Leggere nell’ordine `AGENTS.md`, Memory Bank, spec attiva e ADR pertinenti. Il flusso obbligatorio è:

`spec → test → implementazione minima → verifica → aggiornamento Memory Bank`.

```bash
uv run ruff check .
uv run ruff format --check .
uv run mypy src tests
uv run pytest --cov=italian_energy --cov-branch
pre-commit run --all-files
uv run python scripts/verify_private_golden.py
uv run --extra arera python scripts/verify_arera_import.py
# Smoke live separato, con data esplicita (non usato dalla suite)
uv run python scripts/verify_portal_import.py --date 2026-09-08
```

Il verificatore golden usa soltanto il materiale in `private/` e non pubblica
documenti o identificativi. Le regole normative restano nel fixture pubblico;
prezzi e importi del caso reale restano privati.

## Regulatory Anchor Rollover — Spec 014

`RegulatoryRolloverService` aggiorna la copertura, scopre e acquisisce fonti,
costruisce e verifica un candidate con parser/mapping registrati, lo stagea e
lo promuove con il repository CAS. `refresh_regulatory_anchor` e
`--refresh-anchor` conservano il significato precedente: verificano l'anchor
esistente e non generano il successore.

Il servizio riceve adapter ufficiali e repository tramite protocolli; il Core
mantiene parsing, interpretazione, mapping e scelta dei valori. Il report
restituisce discovery, cursori committabili, candidate, evidenze di coverage,
stato e reason code. La Platform può pianificare il job e persistere questi
artefatti tramite un adapter durevole; tale adapter e il job Platform non sono
inclusi in questo package. `source_preflight` e `resolve_active` sono offline.
Il confronto usa gli snapshot e l'evidenza persistiti, senza riacquisire fonti.

Gli adapter Core coprono gli atti ARERA, gli indici tariffari ARERA, ADM, la
Gazzetta Ufficiale e Normattiva. I parser versionati includono workbook ARERA,
conferme non numeriche della delibera 343, accisa ADM domestica e disposizioni
IVA Normattiva. L'anchor Q4 incluso ha snapshot `2026-10-08`, validità
`[2026-10-01, 2027-01-01)` e ID
`regulatory-anchor:8171d18ee60eac067092ee0e7653c475499da9966fdbcfda55c8770846337e1e`.
La sua evidenza ha `source_preflight.ready=true` per `as_of=2026-10-08`; è
datata e va aggiornata per usare l'anchor in date successive. Il PDF 343 fornito
dall'utente è stato acquisito dalla fonte ufficiale con TLS verificato. La
suite Core usa fixture offline e il confronto resta senza rete; il collaudo
PostgreSQL, il job giornaliero persistente e la promozione concorrente Platform
sono verifiche separate.

## Licenza

Apache License 2.0. Vedere [LICENSE](LICENSE).

## Acquisire il catalogo reale

```bash
python -m italian_energy.integration.catalog_cli --date 2026-09-27
```

La data è esatta e obbligatoria. Il comando acquisisce XML Mercato Libero, CSV
PLACET/parametri e indici storici ufficiali, valida i dati e stampa un riepilogo
JSON con conteggi, digest e copertura temporale degli indici. Exit code: 0 per
l'acquisizione riuscita, 1 per errori Core, 2 per argomenti non validi.
`verified` descrive il catalogo acquisito: non certifica la copertura necessaria
per un confronto economico. I bytes rimangono in memoria; la Platform ne cura
il salvataggio privato e la pianificazione.

## Confronto prospettico beta — Spec 013

La Core locale confronta dodici mesi completi usando lo storico ufficiale più
recente, senza colmare buchi o ripiegare su mesi arretrati. Per il confronto al
27 settembre 2026 la finestra storica è settembre 2025–agosto 2026 e il periodo
stimato è ottobre 2026–settembre 2027. Consumi e indici sono abbinati allo
stesso mese dell'anno. Gli scenari applicano `0.80`, `1.00` e `1.20` al solo
indice energetico; ranking e recommendation usano il base. Ogni costo o
risparmio futuro è un **valore stimato**.

Il mapping automatico verificato è PUN Index GME: media mensile MGP Baseload,
pubblicata in EUR/MWh e convertita in EUR/kWh con `Decimal`. I prezzi medi GME
F1/F2/F3 restano una serie distinta dal PUN e dai codici PE; il Core non li
assegna automaticamente a un'offerta senza un mapping commerciale esplicito.
Il report statistico mensile PDF è la fonte primaria. Solo il suo HTTP 404
esplicito attiva il fallback allo ZIP annuale ufficiale GME; rete, integrità,
layout o parsing non validi restano errori. Il fallback usa la colonna esatta
`PUN INDEX GME` della serie `_15`, controlla tutti i periodi attesi in
`Europe/Rome` (inclusi i giorni con 92 o 100 quarti d'ora) e conserva digest
ZIP e locator OOXML nella provenance. I token numerici restano `Decimal`; la
media interna usa 50 cifre e la conversione divide per 1.000 senza arrotondare
al centesimo. L'acquisizione di più mesi dello stesso anno riusa un solo ZIP.
Il lettore usa `defusedxml` già incluso nelle dipendenze base e non aggiunge
una dipendenza XLSX runtime.
Le componenti ARERA e fiscali sono quelle ufficiali applicabili alla data del
confronto e vengono riutilizzate nel futuro come assunzione, senza prolungare la
la loro validità verificata. L’anchor incluso nel package ha `as_of=2026-10-08`
e validità `2026-10-01`–`2027-01-01` (estremo finale escluso). La coverage
conferma i digest delle fonti e la discovery datata dei provvedimenti
successivi pertinenti; gli hash coincidenti da soli non bastano. Prima di
confronti in date successive, il Core deve produrre nuova evidence aggiornata.

Per ripetere l'acquisizione e la verifica live delle fonti ufficiali, servono
gli extra opzionali `gme` e `arera`:

```bash
uv run --extra gme --extra arera python -m italian_energy.integration.catalog_cli --date 2026-09-27
uv run python -m italian_energy.integration.projection_cli --date 2026-10-08 --refresh-anchor --review regulatory-review.json --output-anchor refreshed-anchor.json
uv run --extra gme --extra arera python -m italian_energy.integration.projection_cli --date 2026-10-08 --verify-sources --review regulatory-review.json --output-sources projected-sources.json
uv run python -m italian_energy.integration.projection_cli --date 2026-10-08 --sources projected-sources.json --request request.json
```

`--refresh-anchor` scarica e verifica le fonti dell'anchor risolto per la data
richiesta, senza acquisire il catalogo o GME. Scrive un envelope
`RegulatoryAnchorRefreshResult` con lo stesso `anchor.as_of`, le nuove date dei
controlli e l'evidenza dei registri; non riscrive né ripubblica il package. Il
comando termina con stato
`review_required` se una fonte cambia, l’anchor non copre la data o manca la
valutazione dei provvedimenti successivi. La classificazione di un atto nuovo
o incerto resta esplicita: il Core non lo dichiara irrilevante tramite hash o
parole chiave. `--verify-sources` è il percorso live completo: acquisisce
catalogo e storico GME, verifica le fonti note e riusa le revisioni contenute
in `RegulatoryCoverageEvidence`. Se manca la revisione degli atti successivi,
il gate resta incompleto anche con tutti i digest corrispondenti.
`--output-sources` salva gli snapshot e l’evidenza in un
`ProjectedSourceBundle` versionato. `--sources` usa quel bundle offline e non
accede alla rete; `--request PATH` accetta un envelope
`ProjectedDomesticComparisonRequest` con `as_of` corrispondente al bundle e
restituisce il confronto tipizzato, marcato `estimated`.

La Platform deve usare `ProjectedDomesticEnergyService.source_preflight(...).ready`
per abilitare globalmente i confronti, insieme alla propria regola di freschezza
del catalogo, e `preflight(request, ...).ready` prima del confronto cliente.
Questo percorso è locale alla Core; l'allineamento e la persistenza Platform
restano separati.

### Handoff Platform del wheel 0.13.7

La Platform mantiene il vincolo `required-version = ">=0.13.0,<0.14.0"`.
Per adottare la wheel Core 0.13.7 occorre verificare digest e attestazioni
dell'artefatto pubblicato, aggiornare pin e SHA-256 puntuali, script di
verifica e immagine, poi rieseguire i gate Platform e il replay economico.
Gli override locali delle sorgenti devono essere rimossi dai servizi che
si dichiarano basati sulla wheel pubblicata. Anche le ottimizzazioni proprie
della Platform devono essere incluse per riprodurre il percorso integrato.

Questa release non modifica schemi o capability e non richiede migrazioni.
L'adozione Platform, la freschezza delle fonti e il deployment rimangono
verifiche separate dalla pubblicazione del package.
