"""Flatten the raw advisory snapshots into two analysis tables.

Usage (from the project folder):
    python code/prepare.py

Reads  data/raw/<snapshot>/page_*.json  (never modified)
Writes data/records.csv   one row per advisory (GHSA ID)
       data/versions.csv  one row per affected-package entry (package + range)

Decisions encoded here:
  * Weeks are Monday to Sunday in UTC (date_trunc('week') in DuckDB).
  * Package keys keep the full scoped name; "@scope/name" is never shortened to "name".
  * A range written "= X" is an explicitly enumerated version. ">= 0" and "> 0"
    are open ranges: they say "every version" and cannot be turned into a
    finite version count from this data. Anything else (one record in this
    snapshot, ">= 2.1.0, <= 2.4.3") is a bounded range: finite, but its members
    are not listed, so it is not counted as exact pairs either.
  * Record style: summaries of the form "Malicious code in <pkg> (npm)" are
    reports imported from the OpenSSF malicious-packages repository (all of
    them cite it); "Malware in <pkg>" records are written by GitHub.
  * Boilerplate: the standard GitHub text that begins "Any computer that has
    this package installed..." and carries no package-specific detail.
"""
from pathlib import Path

import duckdb

ROOT = Path(__file__).resolve().parent.parent
RAW = ROOT / "data" / "raw"
DATA = ROOT / "data"

BOILER = "Any computer that has this package installed%"


def main():
    con = duckdb.connect()
    con.sql("SET TimeZone = 'UTC'")
    con.sql(f"""
        CREATE TABLE adv AS
        SELECT *, split_part(filename, '/', -2) AS snapshot
        FROM read_json('{RAW}/*/page_*.json', format='array', filename=true,
                       union_by_name=true, maximum_object_size=50000000)
    """)
    n, d = con.sql("SELECT count(*), count(DISTINCT ghsa_id) FROM adv").fetchall()[0]
    assert n == d, "the same GHSA ID appears in two snapshots; windows overlap"

    # One row per affected-package entry. UNNEST turns the vulnerabilities list into rows.
    con.sql("""
        CREATE TABLE versions AS
        SELECT ghsa_id,
               v.package.ecosystem AS ecosystem,
               v.package.name      AS package,
               v.vulnerable_version_range AS version_range,
               CASE WHEN v.vulnerable_version_range LIKE '= %'
                    THEN substr(v.vulnerable_version_range, 3) END AS exact_version,
               v.vulnerable_version_range IN ('>= 0', '> 0') AS open_range,
               CASE WHEN v.vulnerable_version_range LIKE '= %' THEN 'exact'
                    WHEN v.vulnerable_version_range IN ('>= 0', '> 0') THEN 'open'
                    WHEN v.vulnerable_version_range IS NULL THEN 'missing'
                    ELSE 'bounded' END AS range_type
        FROM (SELECT ghsa_id, unnest(vulnerabilities) AS v FROM adv)
    """)
    print(con.sql("SELECT range_type, count(*) AS entries FROM versions GROUP BY 1 ORDER BY 2 DESC"))

    con.sql(f"""
        CREATE TABLE records AS
        SELECT a.ghsa_id,
               a.snapshot,
               a.published_at,
               a.updated_at,
               a.withdrawn_at,
               date_trunc('week', a.published_at)::DATE AS week,
               p.package,
               p.n_packages,
               CASE WHEN a.summary LIKE 'Malicious code in % (npm)' THEN 'openssf_import'
                    WHEN a.summary LIKE 'Withdrawn Advisory:%'       THEN 'withdrawn_notice'
                    ELSE 'github_native' END AS style,
               a.description LIKE '{BOILER}' AS boilerplate,
               regexp_extract(a.description, '^## Source: ([A-Za-z0-9_.-]+)', 1) AS report_source,
               length(a.description) AS description_chars,
               p.n_exact, p.has_open_range, p.has_bounded_range,
               len(a."references") AS n_references,
               a.summary
        FROM adv a
        JOIN (SELECT ghsa_id, count(DISTINCT package) AS n_packages, any_value(package) AS package,
                     count(DISTINCT exact_version) AS n_exact, bool_or(open_range) AS has_open_range,
                     bool_or(range_type = 'bounded') AS has_bounded_range
              FROM versions GROUP BY ghsa_id) p USING (ghsa_id)
        ORDER BY a.published_at
    """)
    con.sql(f"COPY records  TO '{DATA}/records.csv'  (HEADER)")
    con.sql(f"COPY (SELECT * FROM versions ORDER BY ghsa_id, exact_version) TO '{DATA}/versions.csv' (HEADER)")

