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

# %% [markdown]
# # A workbook of documents and counts by sector
#
# This program runs each sector's saved search for one month and writes a new Excel workbook.
# Its first sheet lists every document a sector's search found, one row per document and sector,
# with the title in English and Chinese, a summary, the document number, the issuing
# department, the date, the length of the text and the links to the source and to ReConnect
# China. Its second sheet counts the documents by sector, administrative level and province.
#
# It is the monthly update of a register kept in Excel. The saved searches are the ones
# _Saved searches from a keyword workbook_ makes, one per sector, so the keywords stay in your
# keyword sheet and this program only names the searches. The workbook is new every time: copy
# its rows into your own register, or link to it from there.

# %%
import sys
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone

from openpyxl import Workbook
from openpyxl.styles import Alignment, Font
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.worksheet import Worksheet
from reconnectchina import (
    ApiError,
    Client,
    ConsolePrompt,
    Detail,
    HistogramRequests,
    Histograms,
    IssuerHistogramOptions,
    LevelHistogramOptions,
    RunSearchRequest,
    ScopeId,
    SearchFirstPage,
    SearchOverrides,
    SearchPage,
    Summary,
)

# %% [markdown]
# ## What to run
#
# `SAVED_SEARCHES` names the searches to run, one per sector, in the order the workbook lists
# them, and `SCOPE` where they were saved: `account` for your own, `organization` for those
# shared with everyone in your organization. A scope may hold other searches too, on other
# subjects, and a shared one colleagues' searches; that is why the program runs the names you
# list rather than all of them.
#
# `MONTH` is the month to run them for, such as `"2026-08"`. Leave it at `None` for last month,
# counted in China. Naming a month lets you run one you missed. The workbook is named after the
# month: `sectors-2026-08.xlsx`.
#
# `MAX_DOCUMENTS` is how many rows a sector gets at most: its most relevant documents, or its
# newest when the saved search has no term. A register is read by people, and each 32 rows cost
# a request for their detail, so a search that finds tens of thousands of documents a month is
# better narrowed than written out. The counts cover every document either way.

# %%
SAVED_SEARCHES = [
    "energy-efficiency",
    "碳达峰碳中和",
    "digital-economy",
    "wastewater",
    "elderly-care",
]
SCOPE: ScopeId = "account"
MONTH: str | None = None
MAX_DOCUMENTS = 200

# %% [markdown]
# ## Dates in China
#
# The API gives every date as an instant in UTC. A date a source page prints, such as
# 12 May 2026, is midnight in China, which is 16:00 UTC on 11 May. So the calendar date is taken
# in China's time zone, UTC+8, or every printed date comes out a day early. China has kept that
# one offset since 1991, so a fixed offset is enough.
#
# The same goes for the month, and the API can work it out in China's time zone. The program
# sends `2026-08-01[Asia/Shanghai]` as the search's `from`: a date followed by a time zone in
# brackets is midnight at its start in that zone, 16:00 UTC on 31 July. It sends
# `2026-08-01[Asia/Shanghai]+M` as `to`, one calendar month later in the same zone, the first
# instant the search leaves out, so the month ends where the next one begins. `Asia/Shanghai` is
# the name of China's time zone in the time zone database, and it has been UTC+8 since 1991, the
# offset this program shows dates at.


# %%
CHINA = timezone(timedelta(hours=8))


def china_date(instant: datetime | None) -> date | None:
    """The calendar date in China, or nothing when there is no date."""
    if instant is None:
        return None
    return instant.astimezone(CHINA).date()


def last_month(today: date) -> str:
    """The month before the one `today` is in, such as `2026-08`."""
    return f"{today.replace(day=1) - timedelta(days=1):%Y-%m}"


def month_window(month: str) -> tuple[str, str]:
    """Instant expressions for the first instant of `month` in China, and of the next month."""
    first = f"{month}-01[Asia/Shanghai]"
    return first, f"{first}+M"


# %% [markdown]
# ## Finding the saved searches
#
# Before it runs 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, after some sectors have run. Looking them up first lets it name
# every missing search at once and write nothing.
#
# 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`: the API documentation's _Problem types_
# lists each, with what to do about it. Branch on `type`, never on the message, which is written
# for people to read and can change. Any other problem here, such as an account whose access
# has ended, is not something this program can help with, so it 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]
# ## Running one sector's search
#
# The search runs as it was saved, with the month's `from_` and `to` in place of its dates, so
# it keeps to the kinds of document it was saved with: the policy documents. Its
# title is the sector's name, as the keyword sheet gave it, and the workbook shows it in every
# row, so that a formula such as `COUNTIF` can count a sector's rows.
#
# The first page also brings the counts. `histograms` asks for them: how many of the search's
# documents were issued at each administrative level, and how many come from each issuer. They
# count every document the search matches, however far the paging below gets. To have only the
# counts, without any documents, set `page_size=0`.
#
# A document's issuer is the province it concerns, when ReConnect China's classifier finds one;
# failing that, its city or county, or whoever runs the website it came from, such as a
# ministry. So the issuers that are provinces give the counts by province.
#
# Paging works as in _Search results as a CSV file_: follow `next` until a page comes without
# it, and skip a document already seen. It also stops once the sector has `MAX_DOCUMENTS`. When
# fewer documents are written than the search found, the program says so, and why: the limit
# above, or a last page that carries `truncated`, such as at the depth your organization's
# agreement allows a search to page to.


# %%
@dataclass
class Sector:
    title: str
    hits: int
    levels: dict[str, int]
    provinces: dict[str, int]
    summaries: list[Summary]


def run(client: Client, name: str, title: str, month: str) -> Sector:
    start, end = month_window(month)
    first = client.run_saved_search(
        SCOPE,
        name,
        RunSearchRequest(
            parameters=SearchOverrides(
                from_=start,
                to=end,
                page_size=100,
                histograms=HistogramRequests(
                    level=LevelHistogramOptions(), issuer=IssuerHistogramOptions()
                ),
            )
        ),
    )
    histograms = first.histograms or Histograms()

    summaries: dict[str, Summary] = {}
    page: SearchFirstPage | SearchPage = first
    while True:
        for summary in page.summaries:
            summaries.setdefault(summary.id, summary)
        if page.next is None or len(summaries) >= MAX_DOCUMENTS:
            break
        page = client.continue_search(page.next)
    kept = list(summaries.values())[:MAX_DOCUMENTS]

    print(f"{title}: {len(kept)} documents")
    if len(kept) == MAX_DOCUMENTS < first.hits:
        print(
            f"{title}: the search has {first.hits} results, and MAX_DOCUMENTS keeps "
            f"{MAX_DOCUMENTS}. Narrow the search, or raise MAX_DOCUMENTS to get more.",
            file=sys.stderr,
        )
    elif page.truncated is not None:
        print(
            f"{title}: the search has {first.hits} results, and paging stopped before the end "
            f"({page.truncated.reason}). Narrow the search to get the rest.",
            file=sys.stderr,
        )
    return Sector(
        title=title,
        hits=first.hits,
        levels={bucket.level: bucket.hits for bucket in histograms.level or ()},
        provinces={
            bucket.issuer: bucket.hits
            for bucket in histograms.issuer or ()
            if bucket.issuer in PROVINCES
        },
        summaries=kept,
    )


# %% [markdown]
# ## Details
#
# A search result carries most of what the register needs, the link to the source page among
# it, but the issuing department and the text itself are only in a document's detail. The
# program asks for the detail of every document it found, 32 at a time, the most one request
# takes. A document two sectors found is asked for once.
#
# The register gives the length of the text rather than the text: a notice of a few hundred
# characters and a plan of thirty thousand look alike in a list of headlines, and the length
# tells you which to set an afternoon aside for. A document without running text, such as a
# page of attachments, has no length.
#
# Detail comes back in no particular order, so the answers are matched to the documents by
# `id`. An id the API no longer knows comes back under `missing`; its rows are still written,
# from the search result, with those two cells left empty.


# %%
def details(client: Client, ids: list[str]) -> dict[str, Detail]:
    found: dict[str, Detail] = {}
    for start in range(0, len(ids), 32):
        result = client.get_details(ids[start : start + 32])
        for detail in result.detail:
            found[detail.id] = detail
        for id in result.missing:
            print(
                f"No detail for {id}: its rows have no department or length.",
                file=sys.stderr,
            )
    return found


# %% [markdown]
# ## Provinces in English
#
# The API names a province in Chinese, as its government does. The workbook shows the English
# name from this table. A document's _Province_ is its issuer when the issuer is a province,
# and empty when it is a city, a county or a central body, as in the counts by province.

# %%
PROVINCES = {
    "北京市": "Beijing",
    "天津市": "Tianjin",
    "河北省": "Hebei",
    "山西省": "Shanxi",
    "内蒙古自治区": "Inner Mongolia",
    "辽宁省": "Liaoning",
    "吉林省": "Jilin",
    "黑龙江省": "Heilongjiang",
    "上海市": "Shanghai",
    "江苏省": "Jiangsu",
    "浙江省": "Zhejiang",
    "安徽省": "Anhui",
    "福建省": "Fujian",
    "江西省": "Jiangxi",
    "山东省": "Shandong",
    "河南省": "Henan",
    "湖北省": "Hubei",
    "湖南省": "Hunan",
    "广东省": "Guangdong",
    "广西壮族自治区": "Guangxi",
    "海南省": "Hainan",
    "重庆市": "Chongqing",
    "四川省": "Sichuan",
    "贵州省": "Guizhou",
    "云南省": "Yunnan",
    "西藏自治区": "Tibet",
    "陕西省": "Shaanxi",
    "甘肃省": "Gansu",
    "青海省": "Qinghai",
    "宁夏回族自治区": "Ningxia",
    "新疆维吾尔自治区": "Xinjiang",
}


def province(issuer: str) -> str | None:
    return PROVINCES.get(issuer)


# %% [markdown]
# ## Text stays text
#
# Headlines and other fields come straight off the internet. openpyxl writes any text
# beginning with `=` as a formula, which Excel would then run. We avoid this by marking
# every cell as text. You see the same thing in the cell either way.
#
# A cell holds at most 32,767 characters. A summary stays far below that. A document's full
# text can exceed it, and belongs in a file of its own rather than in a cell.

# %%
Value = str | int | 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 documents sheet
#
# One row per document and sector: a document two sectors found has a row in each. _Date_ is a
# date Excel can sort and filter. Every document has one, and _Date kind_ beside it says which
# of its dates it is: `published`, `issued`, `implemented`, or `added`, the day ReConnect China
# collected it, which can be later than the document's own date. _Length_ is the number of
# characters in the Chinese text. _ReConnect China_ is the link to the document on
# reconnectchina.org, and it is how you cite it.
#
# Your organization's agreement can leave out some fields of a document, such as its Chinese
# text. A field left out is absent, and the document's `hidden` names it. Its cell stays empty,
# as _Title (Chinese)_ and _Length_ do for a document whose Chinese text is left out.
#
# The header row stays in view while you scroll, and every column can be filtered.

# %%
COLUMNS = {
    "Sector": 24,
    "Title (English)": 48,
    "Title (Chinese)": 40,
    "Document number": 24,
    "Summary": 80,
    "Level": 10,
    "Province": 14,
    "Type": 20,
    "Issuer": 20,
    "Department": 24,
    "Date": 12,
    "Date kind": 11,
    "Length": 9,
    "Source": 40,
    "ReConnect China": 40,
    "Id": 16,
}
SUMMARY, SOURCE, RC = "Summary", "Source", "ReConnect China"


def row(sector: Sector, summary: Summary, detail: Detail | None) -> list[Value]:
    department = length = None
    if detail is not None:
        department = detail.department
        if detail.zh is not None and detail.zh.body is not None:
            length = sum(len(paragraph) for paragraph in detail.zh.body)
    headline = summary.zh.headline if summary.zh is not None else None
    return [
        sector.title,
        summary.en.title,
        "".join(headline) if headline is not None else None,
        summary.document_number,
        summary.en.summary,
        summary.level,
        province(summary.issuer),
        summary.type,
        summary.issuer,
        department,
        china_date(summary.date),
        summary.date_kind,
        length,
        summary.source,
        summary.rc,
        summary.id,
    ]


def documents(sheet: Worksheet, sectors: list[Sector], found: dict[str, Detail]) -> None:
    sheet.title = "Documents"
    append(sheet, list(COLUMNS), bold=True)
    for sector in sectors:
        for summary in sector.summaries:
            append(sheet, row(sector, summary, found.get(summary.id)))

    names = list(COLUMNS)
    for line in sheet.iter_rows(min_row=2):
        line[names.index(SUMMARY)].alignment = Alignment(wrap_text=True, vertical="top")
        for link in (line[names.index(SOURCE)], line[names.index(RC)]):
            if link.value:
                link.hyperlink = str(link.value)
                link.style = "Hyperlink"
    for number, width in enumerate(COLUMNS.values(), start=1):
        sheet.column_dimensions[get_column_letter(number)].width = width
    sheet.freeze_panes = "A2"
    sheet.auto_filter.ref = sheet.dimensions


# %% [markdown]
# ## The counts sheet
#
# Two tables. _By level_ has a row per sector, with its number of documents and how many of them
# were issued at each administrative level. _By province_ has a row per province and a column
# per sector, from the issuers that are provinces in the table of English names above. The last
# row counts the other issuers: most central documents, and those whose province the classifier
# has not found.
#
# The sectors' counts add up to more than the documents there are, because a document can
# belong to several sectors. That is why each sector is counted by its own search.

# %%
LEVELS = ["centre", "provinces", "cities", "other"]


def labels(known: list[str], counts: list[dict[str, int]]) -> list[str]:
    """The labels in `known`, in their order, then any other the counts hold."""
    return known + sorted({label for count in counts for label in count} - set(known))


def counts(sheet: Worksheet, sectors: list[Sector]) -> None:
    sheet.title = "Counts"
    levels = labels(LEVELS, [sector.levels for sector in sectors])
    provinces = list(PROVINCES)

    append(sheet, ["By level"], bold=True)
    append(sheet, ["Sector", "Documents", *levels], bold=True)
    for sector in sectors:
        append(
            sheet,
            [sector.title, sector.hits, *(sector.levels.get(level, 0) for level in levels)],
        )
    append(sheet, [])
    append(sheet, ["By province"], bold=True)
    append(sheet, ["Province", *(sector.title for sector in sectors)], bold=True)
    for name in provinces:
        append(sheet, [province(name), *(sector.provinces.get(name, 0) for sector in sectors)])
    others = [sector.hits - sum(sector.provinces.values()) for sector in sectors]
    append(sheet, ["Other issuers", *others])
    sheet.column_dimensions["A"].width = 24


# %% [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, and a register with
# dashboards would lose them. Copy the rows over into your own workbook, or link to this one.


# %%
def main(client: Client) -> None:
    month = MONTH or last_month(datetime.now(CHINA).date())
    titles = find_searches(client)
    sectors = [run(client, name, title, month) for name, title in titles.items()]
    ids = list(dict.fromkeys(summary.id for s in sectors for summary in s.summaries))
    found = details(client, ids)

    workbook = Workbook()
    sheet = workbook.active
    assert sheet is not None
    documents(sheet, sectors, found)
    counts(workbook.create_sheet(), sectors)
    output = f"sectors-{month}.xlsx"
    workbook.save(output)
    print(f"{len(ids)} documents 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)
