"""SOURCE render logic for TI-Cal-03 (REFERENCE ONLY).
This is the exact function from our pipeline. It is DB-coupled — you cannot run it without our database.
The query result it produces is materialized for you in data.csv, and the rendered output is figure.json
(load that to display the chart). This file is provided so you can understand / re-theme the logic.
"""
def render_TI_Cal_03(reg: dict) -> dict:
"""Weekly Release Calendar Demand - releases per week of year x mean post-release DI."""
chart_id = "TI-Cal-03"
output_dir = THIS_DIR / chart_id / ROLE
conn = lib.connect_readonly()
t0 = time.time()
# FIX (user: "spiky/spotty"): the old jumpiness came from a sparse exact-release-day DI join.
# Drop it - just count releases per month over 4+ dense years for a clean industry release rhythm.
df = lib.run_query(conn, """
SELECT EXTRACT(MONTH FROM release_date)::integer AS month,
COUNT(DISTINCT imdb_id) AS releases
FROM categorization_release_dates_all
WHERE release_date >= DATE '2022-01-01' AND release_date < DATE '2026-01-01'
GROUP BY EXTRACT(MONTH FROM release_date) ORDER BY month;
""")
q_sec = time.time() - t0
conn.close()
if df.empty:
lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], reg["pc_id"], "No release data")
write_shim(output_dir, chart_id); return {"status": "needs_spec_review"}
df["releases"] = df["releases"].astype(int)
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
months_full = ["January","February","March","April","May","June","July","August","September","October","November","December"]
df["mname"] = df["month"].map(lambda m: months[m - 1])
avg = df["releases"].mean()
colors = [lib.NAVY if v >= avg else lib.PALE_BLUE for v in df["releases"]]
fig = go.Figure()
fig.add_trace(go.Bar(x=df["mname"], y=df["releases"], marker=dict(color=colors), showlegend=False,
hovertemplate="%{x}
%{y:,} titles released (2022-2025)"))
# value labels as annotations: bars whose tops sit near the dashed average line get LIFTED
# so the line can never strike through their numbers (Feb/Jun read as struck-out text before)
for mname, v in zip(df["mname"], df["releases"]):
near_line = abs(float(v) - float(avg)) < 200
fig.add_annotation(x=mname, y=float(v), text=f"{v:,}", showarrow=False,
yanchor="bottom", yshift=16 if near_line else 2,
font=dict(size=10, color=lib.MUTED))
lib.add_ref_line(fig, y=float(avg), label="monthly average")
busy = df.loc[df["releases"].idxmax()]; quiet = df.loc[df["releases"].idxmin()]
title_lesson = (f"The release calendar bunches up: {months_full[int(busy['month']) - 1]} is the busiest month for new titles, "
f"{months_full[int(quiet['month']) - 1]} the quietest")
what = ("How many titles in our tracked catalog were released each month, summed over four full years (2022-2025). Dark bars = "
"above-average months, pale = below - the supply rhythm of when the industry floods the zone and when the field thins out.")
why = ("Release timing is competitive strategy. Launching into a crowded month means fighting for attention; a quiet month offers open "
"air. Paired with the genre-seasonality chart, it shows where the calendar is over-served vs wide open.")
fig.update_layout(**lib.layout_v2(title_lesson, what, width=1200, height=560),
xaxis=lib.standard_xaxis("Month of release"), yaxis=lib.standard_yaxis("Titles released (2022-2025)", tickformat=",d"))
# release-date counts only - no panel data on this chart, so no panel-scope phrase (scope=None)
lib.add_why_and_footer(fig, why, scope_footer(lib.assemble_footer("PC-Cal-03",
["CL-014 external data (release dates, TMDb/IMDb)"], "2025-12-31", ["categorization_release_dates_all"],
"release dates of titles in the PeerLogix-tracked catalog; 4 full years 2022-2025"), scope=None))
lib.save_csv(df, output_dir); lib.export_chart(fig, output_dir, width=1200, height=560)
lib.write_lesson_design(output_dir, chart_id, f"# {chart_id}\n\n{title_lesson}\n\n{what}\n")
write_shim(output_dir, chart_id)
lib.write_manifest(output_dir, chart_id, "ok", reg["spec_file"], pc_id="PC-Cal-03",
intended_lesson_from_spec="Release-volume rhythm by month (de-spiked, multi-year)",
rendered_lesson={"reader_title": title_lesson, "reader_subtitle": what,
"claim_strength": "strong", "rules_applied": "monthly release counts 2022-2025"},
row_count=len(df), freshness_date="2025-12-31",
query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec)
return {"status": "ok", "rows": len(df)}