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

# %% [markdown]
# # Saved searches from a keyword workbook
#
# This program reads a workbook that lists keywords by sector and saves one search per sector
# under a name, finding any of that sector's keywords. You keep the keywords where you already
# keep them, in a spreadsheet, and whenever the sheet changes you run the program again.
#
# A saved search can be run by its name. The other examples do: _Search results as a CSV file_
# runs one saved search, and the sector workbook runs them all. Nobody has to copy keywords from
# one script into another, and when a sector gains a keyword, one run of this program brings
# every script that uses it up to date. The searches are your own unless you share them with
# your colleagues, as _Sharing the searches with colleagues_ below explains.

# %%
import sys
from dataclasses import dataclass, field

from openpyxl import load_workbook
from reconnectchina import (
    ApiError,
    Client,
    ConsolePrompt,
    SaveSearchRequest,
    ScopeId,
    SearchParameters,
    Type,
)

# %% [markdown]
# ## The workbook
#
# `keywords.xlsx`, which comes with this program, has one sheet, _Keywords_, with a header row
# and one keyword per row after it:
#
# | Sector | Saved search | Keyword |
# | --- | --- | --- |
# | Energy efficiency | energy-efficiency | 节能 |
# | Energy efficiency | energy-efficiency | 能效 |
# | Carbon peaking and carbon neutrality | 碳达峰碳中和 | 碳达峰 |
#
# _Saved search_ is the name the sector's search is saved under. A name is made of letters,
# digits, `_` and `-`, in any script, so `碳达峰碳中和` is a name but _Elderly care (养老服务)_
# is not: the spaces and brackets are not allowed. That is why the name has a column of its own
# rather than being made from the sector.
#
# _Sector_ becomes the search's title, which is what people see when a list of saved searches
# is shown to them, and which may be any plain text. A sector needs to be written only once:
# the first row that gives one sets it, and a row may leave it blank after that.
#
# Every search is also saved with a description, `DESCRIPTION` below. A colleague who comes
# across one of these searches learns from it where its keywords are kept, and that a change
# made to the search directly lasts only until this program runs again.
#
# `FROM` and `TO` are the dates every search is saved with: the last seven whole days in China.
# _Saving_ below explains them. `POLICY` is the kinds of document every search keeps to.
# `SCOPE` is where the searches are saved: `account` is yours alone.
#
# To use your own workbook, change these lines. The program finds the columns by their headers,
# so yours may have others too, in any order.

# %%
KEYWORDS = "keywords.xlsx"
SHEET = "Keywords"
SCOPE: ScopeId = "account"
FROM = "now[Asia/Shanghai]-7d/d"
TO = "now[Asia/Shanghai]/d"
POLICY: list[Type] = ["law/decree", "regulation", "notice/announcement", "opinion/plan"]
DESCRIPTION = (
    f"Saved from the sheet {SHEET} of {KEYWORDS}, where its keywords are kept. It finds laws "
    "and decrees, regulations, notices and announcements, opinions and plans, over the last "
    "seven whole days in China unless whoever runs it names other dates. To change the "
    "keywords, change the sheet and run saved_searches_from_keywords.py again: that run "
    "replaces whatever was saved here in between."
)

# %% [markdown]
# ## Reading the sheet
#
# The rows are grouped by the name they are saved under, in the order the sheet has them. A row
# without a keyword is skipped, so blank lines between sectors do no harm. A cell holding a
# number, such as `2030`, is read as the text it shows. Two rows that give one name different
# sectors are a mistake in the sheet, and the program stops at the second.


# %%
@dataclass
class Sector:
    title: str | None = None
    keywords: list[str] = field(default_factory=list)


def text(value: object) -> str:
    return "" if value is None else str(value).strip()


def read_keywords() -> dict[str, Sector]:
    """Each saved-search name, with its sector's title and keywords."""
    workbook = load_workbook(KEYWORDS, read_only=True)
    rows = workbook[SHEET].iter_rows(values_only=True)
    header = [text(value) for value in next(rows)]
    missing = [name for name in ("Sector", "Saved search", "Keyword") if name not in header]
    if missing:
        sys.exit(f"{KEYWORDS}: the sheet {SHEET} has no column {', '.join(missing)}")
    sector_at = header.index("Sector")
    name_at = header.index("Saved search")
    keyword_at = header.index("Keyword")

    searches: dict[str, Sector] = {}
    for number, row in enumerate(rows, start=2):
        keyword = text(row[keyword_at])
        if not keyword:
            continue
        name = text(row[name_at])
        if not name:
            sys.exit(f"{KEYWORDS}: row {number} has a keyword but no saved-search name")
        if name not in searches:
            searches[name] = Sector()
        sector = searches[name]
        title = text(row[sector_at])
        if title and sector.title is None:
            sector.title = title
        elif title and title != sector.title:
            sys.exit(
                f"{KEYWORDS}: row {number} puts {name} in the sector {title}, "
                f"an earlier row in {sector.title}"
            )
        sector.keywords.append(keyword)
    return searches


# %% [markdown]
# ## From keywords to a term
#
# A search's `term` finds any of several keywords when they are joined with `||`. A keyword on
# its own is searched for as a phrase, and only a few characters mean something else: `&&`,
# `||`, `!`, parentheses, `"` and `\`. Keywords rarely hold them, and most of these would work
# without quotes. Quoting every keyword anyway makes it a literal whatever it holds, so the
# program never has to tell which keywords need it. Inside the quotes, a backslash goes before
# any `"` and `\`. The API documentation's _Search terms_ section has the rule.


# %%
def quote(keyword: str) -> str:
    return '"' + keyword.replace("\\", "\\\\").replace('"', '\\"') + '"'


def term(keywords: list[str]) -> str:
    return " || ".join(quote(keyword) for keyword in keywords)


# %% [markdown]
# ## Saving
#
# Each sector's search is saved with `strategy="body"`, which looks for the keywords in the
# documents' text. A search saved under a name that already exists replaces it, title and
# description included.
#
# Each is saved with `type_in=POLICY` as well, which keeps 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. Leave `type_in` out to search every kind, news and reports
# included. A saved search keeps it, so every program that runs the search keeps to these
# kinds too.
#
# It is also saved with `FROM` and `TO`, and a saved search keeps them as they are written, not
# as the dates they meant on the day it was saved. They are instant expressions: `now` is the
# moment the search runs, `[Asia/Shanghai]` makes the date math after it happen in China's time
# zone, `-7d` goes back seven days, and `/d` rounds down to the start of the day there. So
# `now[Asia/Shanghai]-7d/d` to `now[Asia/Shanghai]/d` is the seven days before today in China,
# each from midnight to midnight, whenever anyone runs the search. Without them, a search covers
# `now-7d` to `now`, the last 168 hours, which cuts a day in half at each end. Whoever runs
# the search can still name other dates for that run, as the sector workbook does with a month.
# The instant expressions documentation has the whole language.
#
# The API checks a search when it is saved. A keyword that cannot be read as part of a term,
# a term longer than your organization's agreement allows, or a sector longer than a title may
# be (200 characters), is refused then, while you are looking at the sheet, rather than when a
# colleague runs it next month. The program says which search was refused and why, carries on
# with the next one, and ends with an error if any was refused.
#
# For each search it prints whether it was `created`, under a name new to the scope, or
# `replaced` one saved there before.
#
# It never deletes a saved search: a name that is no longer in your sheet may be one you saved
# by other means, or, in a shared scope, a colleague's. To delete one, use
# `client.delete_saved_search(SCOPE, name)`.
#
# ## Sharing the searches with colleagues
#
# `SCOPE = "account"` saves the searches for you alone: nobody else sees, runs, replaces or
# deletes them. To share them with everyone in your organization, set `SCOPE` to
# `"organization"` here, and have your colleagues set the same `SCOPE` in the programs that run
# the searches, such as the sector workbook. Any of them can then run, replace or delete a
# search saved there.
#
# Whether your organization may share saved searches depends on its agreement, and the sandbox
# never offers it. `client.list_scopes()` lists the scopes you may use; saving to any other is
# refused with the problem type `scope-not-entitled`. A scope keeps its searches apart from
# every other, so the same name in `account` and `organization` is two searches. To move one,
# save it in the other scope and delete the old one.
#
# In a shared scope, `replaced` for a name you have not saved before means a colleague had
# saved a search under it, and yours has taken its place.


# %%
def main(client: Client) -> None:
    searches = read_keywords()
    refused = 0
    for name, sector in searches.items():
        search = SaveSearchRequest(
            title=sector.title,
            description=DESCRIPTION,
            parameters=SearchParameters(
                term=term(sector.keywords),
                strategy="body",
                type_in=POLICY,
                from_=FROM,
                to=TO,
            ),
        )
        try:
            outcome = client.save_search(SCOPE, name, search)
        except ApiError as error:
            refused += 1
            print(f"{name} was not saved: {error}", file=sys.stderr)
            if error.problem is not None:
                for part in error.problem.errors or ():
                    # `pointer` marks a part of the search, `parameter` the scope or the name.
                    print(f"  {part.pointer or part.parameter}: {part.detail}", file=sys.stderr)
            continue
        print(f"{name}: {outcome}, {len(sector.keywords)} keywords")

    if refused:
        sys.exit(f"{refused} of {len(searches)} searches were not saved")


# %% [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)
