# %% [markdown]
# # Model an e-commerce service
#
# A shopper browses a catalogue, adds an item to a cart and checks out. Each action
# makes the web application do some work and query a database. We will describe
# that work, give it a volume of shoppers, and see how e-footprint turns the two
# into infrastructure needs and a carbon footprint.
#
# [Load this scenario in the interface](https://e-footprint.boavizta.org/example/ecommerce/).
#
# We will build the model in layers: hardware, work per request, a shopping
# journey, then demand. After inspecting the result, we will try a smaller page
# payload and compare it with the original model.
#
# The values are illustrative. Both countries use the same laptop, network and
# shopping journey; their electricity mixes differ. Use measurements for your
# service when turning this example into an assessment.

# %% [markdown] {"tags": ["notebook-setup"]}
# ## Before running
#
# Install `efootprint`. The optional charts and graphs also need `efootprint[viz]`
# and Jupyter/IPython. Server sizing uses the Boavizta API;
# `efootprint[boaviztapi]` adds an offline fallback.

# %% [markdown]
# ## Read the modeling inputs
#
# An e-footprint object has a name, inputs and links to other objects. Names help
# us recognize it later in tables and graphs. We will connect the objects as we
# describe the service rather than maintain a separate hardware inventory.
#
# `SourceValue` wraps a numeric input with its unit and provenance. Multiplying by
# `u.GB_stored`, for example, makes a quantity of stored data; `u.GB_ram` describes
# memory. Keeping units on inputs lets calculations convert compatible quantities
# and catches incompatible ones. `SourceObject` wraps inputs such as a provider key
# that are not numeric quantities.

# %% {"tags": ["section:imports"]}
from efootprint.abstract_modeling_classes.source_objects import SourceObject, SourceValue
from efootprint.builders.hardware.boavizta_cloud_server import BoaviztaCloudServer
from efootprint.constants.units import u
from efootprint.core.hardware.server_base import ServerTypes
from efootprint.core.hardware.storage import Storage
from efootprint.core.usage.job import Job

# %%
from efootprint.builders.timeseries import ExplainableHourlyQuantitiesFromFormInputs
from efootprint.constants.countries import Countries
from efootprint.constants.sources import Sources
from efootprint.core.hardware.device import Device
from efootprint.core.hardware.network import Network
from efootprint.core.system import System

# %% {"tags": ["section:journey"]}
from efootprint.core.usage.usage_journey import UsageJourney
from efootprint.core.usage.usage_journey_step import UsageJourneyStep

# %%
from efootprint.core.usage.usage_pattern import UsagePattern
from efootprint.comparison.duplication import duplicate_system
from efootprint.core import attribution
from efootprint.core.lifecycle_phases import LifeCyclePhases
from pathlib import Path

# Choose the destination for files you export in the final section.
output_dir = Path("ecommerce_outputs")
include_calculated_values = False

# %% [markdown] {"tags": ["section:database"]}
# ## Model the database
#
# Let's start with the hardware that holds the product data. `Storage` describes
# the persistent data, while the server describes the machine running the engine.
# Passing `storage=db_storage` connects these objects: it is the storage attached
# to this server, rather than a second independent copy.
#
# `Storage.from_defaults` fills unspecified inputs with defaults and lets us
# override the starting amount of data. `BoaviztaCloudServer.from_defaults` also
# uses a provider and instance type to obtain a reference hardware profile. Here
# that profile is a sizing proxy for an on-premise database. `on_premise()` keeps
# its provisioned capacity available throughout the modeled period.
#
# The engine's background RAM and CPU needs are separate from the work of queries.
# Idle power defaults to zero in this example; replace that assumption with a
# measurement when accounting for idle electricity. Storage accounts for its own
# hardware and energy, so those volumes should not be counted again on the server.

# %% {"tags": ["section:database"]}
db_storage = Storage.from_defaults(
    "Product database storage", base_storage_need=SourceValue(200 * u.GB_stored))
db_server = BoaviztaCloudServer.from_defaults(
    "Product database server", server_type=ServerTypes.on_premise(),
    provider=SourceObject("scaleway"),
    instance_type=SourceObject("ent1-l"),
    base_ram_consumption=SourceValue(2 * u.GB_ram),
    base_compute_consumption=SourceValue(0.1 * u.cpu_core),
    average_carbon_intensity=SourceValue(100 * u.g / u.kWh),
    storage=db_storage)

# %% [markdown] {"tags": ["section:database"]}
# ### Describe query work
#
# A `Job` describes one execution of an operation and links it to the server doing
# the work. Duration says how long its CPU and RAM are occupied. Data transferred
# is the network payload; data stored is the net addition to persistent data.
#
# Keep reads, cart writes and order writes as separate jobs so their different
# resource needs and data growth remain visible. At this stage we describe the
# cost of one operation. The journey and demand will tell us how often it happens.

# %% {"tags": ["section:database"]}
read_catalog = Job(
    "Read product catalog", server=db_server,
    request_duration=SourceValue(20 * u.ms),
    compute_needed=SourceValue(0.1 * u.cpu_core),
    ram_needed=SourceValue(20 * u.MB_ram),
    data_transferred=SourceValue(5 * u.kB),
    data_stored=SourceValue(0 * u.kB_stored))

write_cart = Job(
    "Write cart row", server=db_server,
    request_duration=SourceValue(40 * u.ms),
    compute_needed=SourceValue(0.2 * u.cpu_core),
    ram_needed=SourceValue(50 * u.MB_ram),
    data_transferred=SourceValue(2 * u.kB),
    data_stored=SourceValue(2 * u.kB_stored))

write_order = Job(
    "Write order row", server=db_server,
    request_duration=SourceValue(80 * u.ms),
    compute_needed=SourceValue(0.25 * u.cpu_core),
    ram_needed=SourceValue(80 * u.MB_ram),
    data_transferred=SourceValue(8 * u.kB),
    data_stored=SourceValue(10 * u.kB_stored))

# %% [markdown] {"tags": ["section:web"]}
# ## Model the web application
#
# Now we can describe the application tier with the same building blocks: storage,
# a server, and jobs. The important change is `ServerTypes.autoscaling()`. Its
# instance count follows demand in whole instances, whereas our database remains
# provisioned for the period.
#
# We are still describing what the service needs, without giving it any traffic.
# The usage patterns later in the tutorial will provide the demand used for sizing.

# %% {"tags": ["section:web"]}
web_storage = Storage.from_defaults(
    "Web app local storage", base_storage_need=SourceValue(1 * u.GB_stored))
web_server = BoaviztaCloudServer.from_defaults(
    "Web application server", server_type=ServerTypes.autoscaling(),
    provider=SourceObject("scaleway"),
    instance_type=SourceObject("ent1-s"),
    base_ram_consumption=SourceValue(4 * u.GB_ram),
    base_compute_consumption=SourceValue(0.2 * u.cpu_core),
    average_carbon_intensity=SourceValue(100 * u.g / u.kWh),
    storage=web_storage)

# %% [markdown] {"tags": ["section:web"]}
# ### Describe web requests
#
# Use the same `Job` structure for application requests. Each job below describes
# the web server's part of an action; its database query remains a separate job.
# For example, the catalogue response payload is an application input we can later
# change to explore a design alternative.

# %% {"tags": ["section:web"]}
serve_catalog = Job(
    "Serve catalog page", server=web_server,
    request_duration=SourceValue(120 * u.ms),
    compute_needed=SourceValue(0.1 * u.cpu_core),
    ram_needed=SourceValue(80 * u.MB_ram),
    data_transferred=SourceValue(1.5 * u.MB),
    data_stored=SourceValue(0 * u.kB_stored))

update_cart = Job(
    "Update cart", server=web_server,
    request_duration=SourceValue(60 * u.ms),
    compute_needed=SourceValue(0.05 * u.cpu_core),
    ram_needed=SourceValue(40 * u.MB_ram),
    data_transferred=SourceValue(30 * u.kB),
    data_stored=SourceValue(0 * u.kB_stored))

submit_order = Job(
    "Submit order", server=web_server,
    request_duration=SourceValue(200 * u.ms),
    compute_needed=SourceValue(0.15 * u.cpu_core),
    ram_needed=SourceValue(120 * u.MB_ram),
    data_transferred=SourceValue(80 * u.kB),
    data_stored=SourceValue(0 * u.kB_stored))

# %% [markdown] {"tags": ["section:journey"]}
# ## Connect web and database jobs
#
# We have described individual operations. To represent what happens when someone
# uses the service, put the relevant jobs into a `UsageJourneyStep`.
#
# Browsing the catalogue triggers both `serve_catalog` and `read_catalog`, so they
# belong to the same step. The other steps pair a web request with its database
# write in the same way. Passing the existing job objects connects their work;
# there is no need to recreate the database server or a separate database journey.

# %% {"tags": ["section:journey"]}
browse_step = UsageJourneyStep.from_defaults(
    "Browse the catalog", jobs=[serve_catalog, read_catalog])
cart_step = UsageJourneyStep.from_defaults(
    "Add an item to the cart", jobs=[update_cart, write_cart])
checkout_step = UsageJourneyStep.from_defaults(
    "Check out", jobs=[submit_order, write_order])
# %% [markdown] {"tags": ["section:journey"]}
# ### Assemble the shopping journey
#
# A `UsageJourney` groups these steps into one visit. With this list, each step
# occurs once per journey. We can reuse that journey for different populations
# without recreating its jobs or hardware.

# %% {"tags": ["section:journey"]}
journey = UsageJourney("Shopping journey", uj_steps=[browse_step, cart_step, checkout_step])

# %% [markdown]
# ## Geographic demand
#
# A journey describes one visit. A `UsagePattern` adds who makes that visit, which
# device and network they use, where they are, and how often the visit happens.
# This is the link between a business input such as visits per year and the
# technical work we have just described.
#
# First, define a demand projection. `ExplainableHourlyQuantitiesFromFormInputs`
# turns its starting volume and growth assumptions into hourly occurrences. The
# volume counts complete shopping journeys, rather than individual steps or queries.
# We will use this projection separately for each country.
#
# This generated profile smooths out shopping-hour, weekend and seasonal peaks,
# which limits what it tells us about peak capacity. Custom hourly timeseries can
# represent those variations; edit them in Python and re-export, since the
# interface cannot manually edit their values.

# %%
shopper_volume = {
    "start_date": "2025-01-01",
    "modeling_duration_value": 3,
    "modeling_duration_unit": "year",
    "initial_volume": 1800000,
    "initial_volume_timespan": "year",
    "net_growth_rate_in_percentage": 8,
    "net_growth_rate_timespan": "year",
}
# %% [markdown]
# ### Give the journey a population
#
# `Device.laptop()` and `Network.wifi_network()` choose predefined archetypes for
# the shopper's device and connection. We then create a `UsagePattern` for each
# country, linking the same journey and hardware to a location and demand profile.
#
# Demand is per pattern: reusing `shopper_volume` for two countries gives each of
# them that volume. Their server jobs still point to the same shared infrastructure.
# The `source` argument records where the projection came from; here it is user input.

# %%
laptop = Device.laptop()
wifi = Network.wifi_network()
france_shoppers = UsagePattern(
    "Daily shoppers in France", [journey], [laptop], wifi,
    Countries.FRANCE(),
    ExplainableHourlyQuantitiesFromFormInputs(shopper_volume, source=Sources.USER_DATA))
us_shoppers = UsagePattern(
    "Daily shoppers in the US", [journey], [laptop], wifi,
    Countries.UNITED_STATES(),
    ExplainableHourlyQuantitiesFromFormInputs(shopper_volume, source=Sources.USER_DATA))

# %% [markdown]
# ### Connect the model with System
#
# Pass the usage patterns to `System`. Their links lead to the journey, jobs,
# servers and storage, so the system can discover the infrastructure they use.
# Our model now connects how people use the service to the work and hardware
# needed to support them.

# %% {"tags": ["baseline-end"]}
system = System("E-commerce web and database system", [france_shoppers, us_shoppers], edge_usage_patterns=[])

# %% [markdown]
# ## Inspect numerical results
#
# We can now read calculated attributes from `system`. These are derived from the
# linked inputs: there is no separate calculation to write for every server, job
# or usage pattern. Reading a result computes what it needs; changing an input
# updates the dependent results when they are read again.
#
# `total_footprint` contains hourly emissions. Its `.sum()` gives a total over the
# modeled period, and `.display_quantity` presents the result with a suitable unit.
# The manufacturing and use totals separate the two lifecycle phases.
#
# The loop then asks `attributed_footprint` for each country's share. It adds both
# phases before summing over time. That lets us compare the two usage patterns
# while still sharing the same application and database infrastructure.

# %%
print("Period total:", system.total_footprint.sum().display_quantity)
print("Manufacturing:", sum(system.total_manufacturing_footprint_sum_over_period.values()).display_quantity)
print("Use-phase electricity:", sum(system.total_use_footprint_sum_over_period.values()).display_quantity)
for shoppers in (france_shoppers, us_shoppers):
    attributed = sum(
        (attribution.attributed_footprint(shoppers, phase) for phase in LifeCyclePhases)
    )
    print(shoppers.name, attributed.sum().display_quantity)

# %% [markdown] {"tags": ["plot"]}
# ## Footprint chart
#
# The numerical total tells us the size of the footprint. A breakdown by physical
# source helps us decide what to inspect next: devices, network, servers or storage.
# Look for the largest contributions before refining small assumptions.
#
# The plotting method writes an interactive HTML file; `IFrame` displays that file
# inside the notebook.

# %% {"tags": ["plot"]}
from IPython.display import IFrame, display

system.plot_footprints_by_category_and_object(filename="ecommerce_footprints.html", notebook=False)
display(IFrame("ecommerce_footprints.html", width="100%", height=470))

# %% [markdown] {"tags": ["plot"]}
# ## Follow footprint allocation
#
# The same model can be read from a physical or a functional perspective. The
# Sankey connects hardware and electricity to the jobs, journey steps and shoppers
# they support. Follow a shared server's flow to see how its impact is allocated
# between the country patterns.
#
# Each successive column redistributes the same period footprint. Adding column
# totals would count that footprint repeatedly. Hover over flows for amounts and
# percentages; small contributions may be grouped.

# %% {"tags": ["plot"]}
from efootprint.utils.impact_repartition import ImpactRepartitionSankey

ImpactRepartitionSankey(system).figure(filename="ecommerce_sankey.html", height=650, width=1100)
display(IFrame("ecommerce_sankey.html", width="100%", height=700))

# %% [markdown] {"tags": ["plot"]}
# ## Inspect the shopping relationships
#
# Start from the system to see how the French and US shopping patterns share
# one journey. Follow that journey through its steps, jobs and hardware. Each
# line shows a relationship between model objects.
#
# The graph hides the system node, countries, devices, network and storage to
# keep the service calls readable. The footprint calculations still account for
# these model inputs.

# %% {"tags": ["plot"]}
system.object_relationship_graph_to_file(
    filename="ecommerce_relationships.html", notebook=True, width="100%", height="550px",
    classes_to_ignore=["System", "Country", "Device", "Network", "Storage"],
)
display(IFrame("ecommerce_relationships.html", width="100%", height=600))

# %% [markdown]
# ## Follow a calculation
#
# A result can be traced back to the inputs that produced it. Call `.explain()` on
# `web_server.power` to inspect its calculation and sources. Here the power estimate
# comes from the Boavizta hardware profile, so that profile is an assumption to
# check if server electricity is important in the result.

# %%
print(web_server.power.explain())

# %% [markdown] {"tags": ["plot"]}
# The calculus graph expands this explanation into formulas and dependencies.
# Unlike the object-relationship graph, it follows a calculated quantity back
# through the calculations that produced it. Hover over nodes to inspect them;
# `max_depth` limits how much of that calculation is displayed.

# %% {"tags": ["plot"]}
web_server.power.calculus_graph_to_file(filename="ecommerce_power_graph.html", notebook=True, max_depth=3, width="100%", height="450px")
display(IFrame("ecommerce_power_graph.html", width="100%", height=500))

# %% [markdown] {"tags": ["plot"]}
# ## Read hourly and cumulative server footprints
#
# An aggregate total can hide how emissions change with demand. Calling `.plot()`
# on the server's use footprint shows the amount emitted in each hourly bin.
# Adding `cumsum=True` instead accumulates those amounts from the start.
#
# Each hourly point is a mass of CO2-eq for that hour. A cumulative point is the
# mass emitted since the model began, so a rising cumulative curve alone does not
# mean hourly emissions are increasing. Neither curve includes manufacturing.
#
# These are the shared web server's emissions across both countries. Steps can
# appear when demand requires another server instance.

# %% {"tags": ["plot"]}
web_server.use_footprint.plot(filepath="ecommerce_hourly_use.png", plt_show=True)
web_server.use_footprint.plot(filepath="ecommerce_cumulative_use.png", cumsum=True, plt_show=True)

# %% [markdown]
# ## Compare a smaller catalogue page
#
# Let's test a change while keeping the original model available for comparison.
# `duplicate_system` copies the model and preserves the IDs of corresponding
# objects. The copied system gets its own ID, allowing the interface to match
# objects across the two scenarios.
#
# Find the catalogue job inside the copy by its retained ID, then change that
# job's payload. Editing `serve_catalog` itself would change the original model.
# The next reads of the two totals use their respective inputs automatically.
#
# This comparison holds demand and the rest of the service constant. Interpret
# the difference as the effect of this intervention under the model's assumptions.

# %%
smaller_pages = duplicate_system(system)
smaller_pages.name = "E-commerce with smaller catalogue pages"
variant_catalog_job = next(
    obj for obj in smaller_pages.all_linked_objects if obj.id == serve_catalog.id
)
variant_catalog_job.data_transferred = SourceValue(0.75 * u.MB)
print("Original:", system.total_footprint.sum().display_quantity)
print("Smaller pages:", smaller_pages.total_footprint.sum().display_quantity)
print("Difference:", (smaller_pages.total_footprint - system.total_footprint).sum().display_quantity)

# %% [markdown]
# ## Export to the interface
#
# You can continue exploring the model in the
# [e-footprint interface](https://e-footprint.boavizta.org/). Set `output_dir` near
# the start, then use `system_to_json` to write the original model. `systems_to_json`
# writes the comparison: the first system is the reference and the second is the
# smaller-page variant.
#
# The single-model file contains inputs only by default. These are enough to load
# the model and calculate results. Set `include_calculated_values = True` to also
# save complete calculated snapshots of both models. Otherwise, comparison files
# include the calculated results already available on each model.
#
# Open the single-model file to inspect or edit one scenario, or the comparison
# file to examine the change side by side.

# %%
from efootprint.api_utils.system_to_json import (
    materialize_serialized_state, system_to_json, systems_to_json,
)

output_dir.mkdir(parents=True, exist_ok=True)
if include_calculated_values:
    materialize_serialized_state(system)
    materialize_serialized_state(smaller_pages)
system_to_json(
    system, save_computed_state=include_calculated_values,
    output_filepath=str(output_dir / "ecommerce.json"),
)
systems_to_json(
    [system, smaller_pages], output_filepath=str(output_dir / "ecommerce_comparison.json"),
)
print("Exported model and reference-first comparison to", output_dir)
