# /// script
# requires-python = ">=3.11"
# dependencies = ["reconnectchina>=12.0", "openpyxl>=3.1"]
# ///

# %% [markdown]
# # Monthly counts by sector, with a chart
#
# This program counts each sector's policy documents per month over the last eleven whole
# months, and all policy documents over the same months, and writes a new Excel workbook with
# the counts, each sector's share per 1,000 policy documents, and a line chart of each. It
# answers whether a subject is rising, and whether it rises faster than policy as a whole.
#
# The saved searches are the ones _Saved searches from a keyword workbook_ makes, one per
# sector. The months are months in China, chosen with date math: an expression such as
# `now[Asia/Shanghai]/M-11M`, which the API evaluates when the request arrives, so the program
# covers the latest months whenever it runs and needs no editing from one month to the next.

# %%
import sys
from datetime import date, timedelta

from openpyxl import Workbook
from openpyxl.chart import LineChart, Reference
from openpyxl.styles import Font
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.worksheet import Worksheet
from reconnectchina import (
    ApiError,
    Client,
    ConsolePrompt,
    HistogramRequests,
    Histograms,
    RunSearchRequest,
    ScopeId,
    SearchOverrides,
    SearchParameters,
    TimeBucket,
    TimeHistogramOptions,
    TimeZone,
    Type,
)

# %% [markdown]
# ## What to run
#
# `SAVED_SEARCHES` names the searches to count, one per sector, in the order the workbook shows
# them, and `SCOPE` where they were saved: `account` for your own, `organization` for those
# shared with everyone in your organization.
#
# `ZONE` is the time zone whose months are counted, China's. `FROM` and `TO` are the months to
# count, as instant expressions in that zone: `FROM` is the first instant counted and `TO` the
# first instant left out. The next two sections explain them and how to write others.
#
# `POLICY` is the kinds of document counted as all policy documents, the kinds the saved
# searches keep to: _Counting_ below explains it.

# %%
SAVED_SEARCHES = [
    "energy-efficiency",
    "碳达峰碳中和",
    "digital-economy",
    "wastewater",
    "elderly-care",
]
SCOPE: ScopeId = "account"
ZONE: TimeZone = "Asia/Shanghai"
FROM = f"now[{ZONE}]/M-11M"
TO = f"now[{ZONE}]/M"
POLICY: list[Type] = ["law/decree", "regulation", "notice/announcement", "opinion/plan"]

# %% [markdown]
# ## Date math
#
# An instant expression starts from a point in time, here `now`, the moment the request
# arrives, and applies its operations from left to right. `[Asia/Shanghai]` says that they
# happen in China's time zone, `/M` rounds down to the start of the month there, and `-11M`
# goes back eleven months. On 29 September 2026:
#
# - `TO`, `now[Asia/Shanghai]/M`, is midnight on 1 September in China, `2026-08-31T16:00:00Z`;
# - `FROM`, `now[Asia/Shanghai]/M-11M`, is eleven months before that, midnight on 1 October 2025
#   in China.
#
# So the program counts October 2025 to August 2026. September is left out on purpose: a month
# still in progress has only some of its documents, and on a chart it looks like a fall.
#
# Why eleven months and not twelve: how far back a search may reach depends on your
# organization's agreement, often one year, `now-1y`. Twelve months back would be the 1st of
# September 2025, a few weeks further back than that, and the API refuses it with a problem of
# the type `range-not-entitled`, whose message names the earliest `FROM` you may use. If your
# agreement reaches further, go back further. The agreement bounds how far ahead `TO` may reach
# too, which a `TO` in the past never meets. A fixed date is an instant expression as well:
# `FROM = "2026-01-01[Asia/Shanghai]"` counts this year's whole months.
#
# A saved search can keep date math too. Saved with `from` set to `now[Asia/Shanghai]/M-11M`, a
# search means the last eleven whole months in China every time anyone runs it, not the months
# it was saved in.
#
# The program itself works out no dates. The API answers with the months it counted, each with
# its start and end, and the workbook is named after the first and the last:
# `trends-2025-10-to-2026-08.xlsx`.

# %% [markdown]
# ## Months in China
#
# The histogram counts months in UTC unless it is told otherwise, whatever zone `FROM` and `TO`
# name. So the program gives it the same zone, `time_zone=ZONE`. A date a source page prints,
# such as 1 August 2026, is midnight in China, 16:00 UTC on 31 July, and counted in UTC months
# it would fall into July. Counted in China's, it falls into August, where the page put it.
#
# Name the zone in all three places. A histogram in UTC over months that begin in China would
# start with a sliver: the last eight hours of September 2025 in UTC, counted as a month of
# their own.
#
# `Asia/Shanghai` is China's time zone as the time zone database names it. For a reader in
# Berlin counting the days documents were collected, `added`, `Europe/Berlin` would be the zone,
# with its summer time; the instant expressions documentation lists what a zone can be.
#
# Each month the API answers with still has its bounds in UTC: August in China runs from
# `2026-07-31T16:00:00Z` to `2026-08-31T16:00:00Z`, so the date of its start in UTC is a day
# early. The program names a month by its middle instead, which lies inside the month in any
# zone.
#
# A range of 92 days or less is counted per day rather than per month. This program charts
# months, so it asks for a longer range when it gets days.


# %%
def month(bucket: TimeBucket) -> date:
    """The month a bucket counts, as its first day, taken from the bucket's middle."""
    if bucket.to - bucket.from_ < timedelta(days=28):
        sys.exit(
            f"FROM {FROM!r} to TO {TO!r} is counted per day, which happens for 92 days or "
            "less. This program charts months: make the range longer."
        )
    middle = bucket.from_ + (bucket.to - bucket.from_) / 2
    return middle.date().replace(day=1)


# %% [markdown]
# ## Finding the saved searches
#
# Before it counts anything, the program looks up every name in `SAVED_SEARCHES`, which also
# gives it each search's title. A name nobody has saved, or one misspelt here, would otherwise
# stop the program halfway. Looking them up first lets it name every missing search at once.
#
# When the API refuses a request, the client raises an `ApiError`, and its `type` says which
# problem it was, such as `saved-search-not-found`. Branch on `type`, never on the message,
# which is written for people to read and can change. Any other problem is raised again and
# ends the program with its message.
#
# A saved search is looked up in `SCOPE` alone. One a colleague saved in their own `account` is
# theirs, and not found in yours: to run it, they save it in `organization` and you set
# `SCOPE = "organization"` (see _Saved searches from a keyword workbook_).


# %%
def find_searches(client: Client) -> dict[str, str]:
    """The title of each saved search in `SAVED_SEARCHES`, by name."""
    titles: dict[str, str] = {}
    missing: list[str] = []
    for name in SAVED_SEARCHES:
        try:
            titles[name] = client.get_saved_search(SCOPE, name).title or name
        except ApiError as error:
            if error.type != "saved-search-not-found":
                raise
            missing.append(name)
    if missing:
        sys.exit(
            f"No saved search is called {', '.join(missing)} in the scope {SCOPE}. Save "
            "them with saved_searches_from_keywords.py, or change SAVED_SEARCHES or SCOPE."
        )
    return titles


# %% [markdown]
# ## Counting
#
# Each saved search runs with `FROM` and `TO` in place of its own dates, and asks for the
# `time` histogram: its hits per month. `page_size=0` asks for the counts alone, without any
# documents, so each sector costs one request.
#
# One more search, without a term, counts all policy documents over the same months. A sector
# that grows may only grow with everything else, when more documents are published or collected
# overall; its share of all policy documents shows which it is.
#
# The saved searches keep to the kinds of document that set or announce policy: laws and
# decrees, regulations, notices and announcements, opinions and plans. ReConnect China's
# classifier assigns each document its kind, as the API documentation's _Type_ explains. So
# this search keeps to the same kinds, `type_in=POLICY`, and the shares compare like with
# like. A sector counted over every kind would need a baseline over every kind as well.


# %%
Counts = dict[date, int]

HISTOGRAM = HistogramRequests(time=TimeHistogramOptions(time_zone=ZONE))


def per_month(buckets: tuple[TimeBucket, ...] | None) -> Counts:
    return {month(bucket): bucket.hits for bucket in buckets or ()}


def sector(client: Client, name: str) -> Counts:
    overrides = SearchOverrides(from_=FROM, to=TO, page_size=0, histograms=HISTOGRAM)
    first = client.run_saved_search(SCOPE, name, RunSearchRequest(parameters=overrides))
    return per_month((first.histograms or Histograms()).time)


def everything(client: Client) -> Counts:
    parameters = SearchParameters(
        type_in=POLICY, from_=FROM, to=TO, page_size=0, histograms=HISTOGRAM
    )
    first = client.search(parameters)
    return per_month((first.histograms or Histograms()).time)


# %% [markdown]
# ## Text stays text
#
# A sector's title is text someone typed, and openpyxl writes any text beginning with `=` as a
# formula, so every text cell is marked as text. You see the same thing in the cell either way.

# %%
Value = str | int | float | date | None


def append(sheet: Worksheet, values: list[Value], bold: bool = False) -> None:
    sheet.append(values)
    for cell in sheet[sheet.max_row]:
        if isinstance(cell.value, str):
            cell.data_type = "s"
        if bold:
            cell.font = Font(bold=True)


# %% [markdown]
# ## The workbook
#
# _Counts_ has a row per month: the month, all policy documents, and each sector's documents.
# _Per 1,000_ has each sector's documents per 1,000 of all policy documents that month, left
# empty for a month without any. The months are dates Excel can sort and filter, shown as
# `Aug 2026`.
#
# The sectors' counts add up to more than there are documents, because a document can belong to
# several sectors. That is why each sector is counted by its own search.
#
# Each sheet has a line chart of its sectors beside the table. The chart on _Counts_ leaves out
# all policy documents, which would dwarf the sectors.


# %%
def chart(sheet: Worksheet, title: str, first_column: int) -> None:
    """A line per column from `first_column` on, over the months in column A."""
    line = LineChart()
    line.title = title
    line.width, line.height = 24, 12
    rows = sheet.max_row
    data = Reference(
        sheet, min_col=first_column, max_col=sheet.max_column, min_row=1, max_row=rows
    )
    line.add_data(data, titles_from_data=True)
    line.set_categories(Reference(sheet, min_col=1, min_row=2, max_row=rows))
    line.x_axis.number_format = "mmm yyyy"
    # openpyxl hides both axes unless told otherwise.
    line.x_axis.delete = line.y_axis.delete = False
    sheet.add_chart(line, f"{get_column_letter(sheet.max_column + 2)}2")


def table(sheet: Worksheet, header: list[str], rows: list[list[Value]], fmt: str) -> None:
    append(sheet, [*header], bold=True)
    for values in rows:
        append(sheet, values)
    for line in sheet.iter_rows(min_row=2):
        line[0].number_format = "mmm yyyy"
        for cell in line[1:]:
            cell.number_format = fmt
    sheet.column_dimensions["A"].width = 12
    for number in range(2, len(header) + 1):
        sheet.column_dimensions[get_column_letter(number)].width = 18
    sheet.freeze_panes = "A2"


def share(hits: int, total: int) -> float | None:
    return hits * 1000 / total if total else None


# %% [markdown]
# ## Putting it together
#
# The workbook is a new file every time; the program never opens yours to fill it in. openpyxl
# cannot keep the charts and images of a workbook it opens and saves again. Copy the rows over
# into your own workbook, or link to this one.


# %%
def main(client: Client) -> None:
    titles = find_searches(client)
    sectors = {title: sector(client, name) for name, title in titles.items()}
    total = everything(client)
    months = sorted(total)
    if not months:
        sys.exit(f"FROM {FROM!r} to TO {TO!r} holds no month.")

    workbook = Workbook()
    counts = workbook.active
    assert counts is not None
    counts.title = "Counts"
    table(
        counts,
        ["Month", "All policy documents", *sectors],
        [[m, total[m], *(s.get(m, 0) for s in sectors.values())] for m in months],
        "#,##0",
    )
    chart(counts, "Documents per month", first_column=3)

    shares = workbook.create_sheet("Per 1,000")
    table(
        shares,
        ["Month", *sectors],
        [[m, *(share(s.get(m, 0), total[m]) for s in sectors.values())] for m in months],
        "0.0",
    )
    chart(shares, "Documents per 1,000 policy documents", first_column=2)

    output = f"trends-{months[0]:%Y-%m}-to-{months[-1]:%Y-%m}.xlsx"
    workbook.save(output)
    print(f"{len(months)} months of {len(sectors)} sectors written to {output}")


# %% [markdown]
# ## Logging in and running it
#
# The program asks you to log in every time it runs: it prints a link, you open it and log in
# with your reconnectchina.org account, and the login ends with the program. Nothing is saved,
# so there is no secret to keep safe.
#
# A program that runs again and again, or with nobody at the keyboard, can keep a login in a
# file instead: see _Creating a token for a script_ in the API documentation.

# %%
if __name__ == "__main__":
    # The API is for partner organizations. To try the example on the sandbox, which every
    # account in an organization can use, pass server="https://sandbox.api.reconnectchina.org".
    client = Client(prompt=ConsolePrompt())
    main(client)
