#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Stileex measured requirements bench: from the analysis of a campaign to the published data.
#
#   publier.py --analyse results.json --fiche apps/<app>/fiche.json \
#              --date YYYY-MM-DD --parution YYYY-MM-DD --sortie <directory>
#
# Writes, in the directory:
#   - <app>.json and <app>.csv, the measurement of the application, which envoyer.sh delivers to
#     stileex.xyz, where its page, the API and the open data read it (never typed by hand);
#   - toutes.json and toutes.csv, every application together;
#   - archives/<app>/, the data published before, kept as it was when a measurement of another
#     version, day or method replaces it, and listed in `historique`.
# Refuses to write a profile whose runs did not all hold, whose two runs are more than 10 % apart
# without a third, or a size that was not validated: a figure that is not measured and held is not
# published.

import argparse
import csv
import glob
import io
import json
import os
import sys

PROFILS = ('idle', 'light', 'sustained')
METHODE = '1.1'
SOURCE = 'Stileex, https://stileex.xyz/'
# The profile replayed at the candidate size (method 1.1): the heaviest one.
PROFIL_VALIDE = 'sustained'
# The scale of sizes, the same as analyse.py's (method 1.1, Simon, 2026-11-29).
ECHELLE_MEMOIRE_MIO = (512, 1024, 2048, 4096, 8192, 16384)

# metric of the analysis -> (published name, unit)
PUBLIEES = [
    ('pile_ws_mediane', 'memoire_travail_mediane', 'octets'),
    ('pile_ws_p95', 'memoire_travail_p95', 'octets'),
    ('pile_ws_pic', 'memoire_travail_pic', 'octets'),
    ('pile_cpu_moyenne', 'cpu_moyenne', 'vcpu'),
    ('pile_cpu_p95', 'cpu_p95', 'vcpu'),
    ('ct_ws_mediane', 'serveur_memoire_travail_mediane', 'octets'),
    ('ct_ws_pic', 'serveur_memoire_travail_pic', 'octets'),
    ('ct_memory_peak', 'serveur_memory_peak', 'octets'),
    ('ct_cpu_p95', 'serveur_cpu_p95', 'vcpu'),
    ('disque_lecture_moyenne', 'disque_lecture_moyenne', 'octets_par_seconde'),
    ('disque_ecriture_moyenne', 'disque_ecriture_moyenne', 'octets_par_seconde'),
    ('publication_p95_ms', 'scenario_p95', 'ms'),
    ('livraison_p95_ms', 'scenario_livraison_p95', 'ms'),
    ('taux_erreur', 'taux_erreur', 'ratio'),
    ('taux_livraison', 'taux_livraison', 'ratio'),
    ('taux_servfail', 'taux_reponses_amont_en_echec', 'ratio'),
]


def arrondi(v, unite):
    if v is None:
        return None
    if unite == 'octets' or unite == 'octets_par_seconde':
        return int(round(v))
    if unite == 's':
        return round(v, 3)
    return round(v, 6)


def plage(agregat, unite='ratio'):
    if not agregat:
        return None
    return {'mediane': arrondi(agregat['mediane'], unite), 'min': arrondi(agregat['min'], unite),
            'max': arrondi(agregat['max'], unite), 'n': agregat['n']}


def stat(values, unite):
    values = sorted(v for v in values if v is not None)
    if not values:
        return None
    n = len(values)
    med = values[n // 2] if n % 2 else (values[n // 2 - 1] + values[n // 2]) / 2
    return {'mediane': arrondi(med, unite), 'min': arrondi(values[0], unite), 'max': arrondi(values[-1], unite), 'n': n}


def main():
    p = argparse.ArgumentParser(description='publishes the analysis of a campaign')
    p.add_argument('--analyse', required=True)
    p.add_argument('--fiche', required=True)
    p.add_argument('--date', required=True, help='day of the campaign, YYYY-MM-DD')
    p.add_argument('--parution', required=True, help='publication day of the measurement: YYYY-MM-DD')
    p.add_argument('--sortie', required=True, help='directory of the published measurements')
    args = p.parse_args()

    analyse = json.load(open(args.analyse))
    fiche = json.load(open(args.fiche))
    app = fiche['id']
    if analyse.get('methode') != METHODE:
        sys.exit(f'the analysis was made with method {analyse.get("methode")}, this script publishes {METHODE}')

    profils = {}
    meta_banc = None
    images = None
    installation = {'reponse_saine_s': [], 'pic': [], 'pic_serveur': [], 'memory_peak_serveur': [], 'donnees': []}
    croissance = None
    socle = None
    for cle in PROFILS:
        prof = analyse['profils'].get(cle)
        if not prof:
            sys.exit(f'{cle}: no run in the analysis')
        if len(prof['passages']) < 2:
            sys.exit(f'{cle}: {len(prof["passages"])} run, two at least')
        if not prof['tenu_partout']:
            sys.exit(f'{cle}: a run did not hold, nothing is published')
        if not prof['valide_partout']:
            sys.exit(f'{cle}: a run was taken on a busy host, replay it first')
        if prof['troisieme_passage']:
            sys.exit(f'{cle}: spread above 10 % on {prof["ecarts"]}, play the third run first')
        if prof['ecarts_a_rejouer']:
            sys.exit(f'{cle}: spread above 10 % on {prof["ecarts_a_rejouer"]} after three runs, investigate')
        passages = prof['passages']
        meta_banc = meta_banc or passages[0]['meta']
        images = images or passages[0]['images']
        a = prof['agregats']
        profils[cle] = {
            'utilisateurs': fiche['profils'][cle]['utilisateurs'],
            'jeu_de_donnees': fiche['profils'][cle]['jeu_de_donnees'],
            'passages': len(passages),
            'mesures': {nom: plage(a.get(source), unite) for source, nom, unite in PUBLIEES if a.get(source)},
            # The highest working set peak of the whole server (system, Docker and the stack), first
            # start included, and the memory to plan for this profile: that peak plus 25 %.
            'pic_serveur_octets': int(round(prof['a_prevoir']['pic_serveur_octets'])),
            'memoire_a_prevoir_octets': int(round(prof['a_prevoir']['memoire_octets'])),
        }
        installation['reponse_saine_s'] += [x['installation']['premiere_reponse_saine_s'] for x in passages]
        installation['pic'] += [x['installation']['pile_ws_pic'] for x in passages]
        installation['pic_serveur'] += [x['installation'].get('ct_ws_pic') for x in passages]
        installation['memory_peak_serveur'] += [x['installation'].get('ct_memory_peak') for x in passages]
        installation['donnees'] += [x['meta']['taille_installee'] for x in passages]
        # The disk growth per 1,000 units is published only from a dataset of 1,000 units or more:
        # below, it would be an extrapolation, and no estimated figure is ever published.
        if a.get('croissance_disque_par_1000') and fiche['profils'][cle]['jeu_de_donnees'] >= 1000:
            croissance = plage(a['croissance_disque_par_1000'], 'octets') if croissance is None else croissance
        if cle == 'idle':
            socle = plage(a['socle_ws_mediane'], 'octets')

    # The size: the smallest one of the scale that holds every profile, validated by a replay of the
    # sustained profile at that size. A replay that did not hold sends to the next size up, which then
    # needs its own held replay.
    candidate = analyse['taille_candidate']
    if not candidate or candidate['memoire_mio'] is None or candidate['vcpu'] is None:
        sys.exit('no size of the scale holds this application')
    # Replays taken on a quiet host, by size. Walking up the scale from the candidate: a size whose
    # replays all held is the validated one; a size whose replay failed sends to the next one; a size
    # never replayed stops the walk, so that a larger size validated earlier (the 1.0 tiers) is never
    # published in place of the candidate.
    rejoues = {}
    for v in analyse['validations']:
        if v['meta']['profil'] == PROFIL_VALIDE and v['meta']['vcpu'] == candidate['vcpu'] and v['validite']['valide']:
            rejoues.setdefault(v['meta']['memoire_mio'], []).append(v)
    validee = None
    for mio in ECHELLE_MEMOIRE_MIO:
        if mio < candidate['memoire_mio']:
            continue
        if mio not in rejoues:
            break
        if all(x['tenu'] for x in rejoues[mio]):
            validee = (mio, candidate['vcpu'])
            break
    if validee is None:
        sys.exit(f'size {candidate["vcpu"]} vCPU, {candidate["memoire_mio"]} MiB not validated by a held replay of the {PROFIL_VALIDE} profile')
    validations = rejoues[validee[0]]
    taille = {
        'vcpu': validee[1], 'memoire_mio': validee[0],
        'memoire_a_prevoir_octets': int(round(candidate['memoire_a_prevoir_octets'])),
        'cpu_p95_vcpu': round(candidate['cpu_p95_vcpu'], 6),
        'profil_valide': PROFIL_VALIDE,
        'validation': {'passages': len(validations), 'dossiers': [v['dossier'] for v in validations]},
    }

    faits = {
        'id': app, 'nom': fiche['nom'], 'categorie': fiche['categorie'], 'site': fiche['site'],
        # The licence of the measured SOFTWARE; the licence of the published DATA is `licence` (CC BY 4.0).
        'depot': fiche['depot'], 'licence_logiciel': fiche['licence'], 'guide': fiche.get('guide'),
        'unite': fiche['unite'],
        'version': meta_banc['version'],
        # The reference as it is pinned: name, tag and digest (Docker reports name@digest only).
        'images': [{'ref': i['digest'].replace('@', f':{meta_banc["version"]}@', 1) if ':' not in i['digest'].split('@')[0] else i['digest'],
                    'taille_octets': i['taille']} for i in images],
        'date': args.date,
        'parution': args.parution,
        'methode': METHODE,
        'banc': {k: meta_banc[k] for k in ('processeur', 'fils_hote', 'noyau', 'proxmox', 'systeme', 'docker', 'compose', 'k6')},
        'banc_large': {'vcpu': meta_banc['vcpu'], 'memoire_mio': meta_banc['memoire_mio']},
        'socle': socle,
        'installation': {'reponse_saine_s': stat(installation['reponse_saine_s'], 's'),
                         'pic_memoire_travail': stat(installation['pic'], 'octets'),
                         'pic_serveur': stat(installation['pic_serveur'], 'octets'),
                         'memory_peak_serveur': stat(installation['memory_peak_serveur'], 'octets'),
                         'donnees_octets': stat(installation['donnees'], 'octets')},
        'croissance_disque_par_1000': croissance,
        'taille': taille,
        'profils': profils,
        'documentation': fiche['documentation'],
        # What differs from the application's default configuration, by kind (the text is the pages').
        'ecarts': fiche.get('ecarts', []),
    }

    dossier = args.sortie
    os.makedirs(dossier, exist_ok=True)

    # The history: the data published before stays where it was published, and is listed here. Only a
    # publication of another version, day or method replaces it; the same campaign published again
    # (a correction of the page) keeps the history as it was.
    historique = []
    courant = os.path.join(dossier, f'{app}.json')
    if os.path.exists(courant):
        ancien = json.load(open(courant))
        historique = ancien.pop('historique', None) or []
        if (ancien.get('version'), ancien.get('date'), ancien.get('methode')) != (faits['version'], faits['date'], METHODE):
            nom = f'{ancien["version"]}_{ancien["date"]}_methode-{ancien["methode"]}.json'
            os.makedirs(os.path.join(dossier, 'archives', app), exist_ok=True)
            with open(os.path.join(dossier, 'archives', app, nom), 'w') as f:
                json.dump(ancien, f, indent=1, ensure_ascii=False)
                f.write('\n')
            historique = [{'version': ancien['version'], 'date': ancien['date'], 'methode': ancien['methode'],
                           'donnees': f'archives/{app}/{nom}'}] + historique
    faits['historique'] = historique

    with open(courant, 'w') as f:
        json.dump({**faits, 'licence': 'CC BY 4.0', 'source': SOURCE}, f, indent=1, ensure_ascii=False)
        f.write('\n')

    # Every application together, from the JSON files already published (without their own copy of
    # the data licence and source, which toutes.json carries once).
    toutes = []
    for path in sorted(glob.glob(os.path.join(dossier, '*.json'))):
        if os.path.basename(path) != 'toutes.json':
            d = json.load(open(path))
            d.pop('source', None)
            d.pop('licence', None)
            toutes.append(d)
    lignes = []
    for d in toutes:
        t = d.get('taille') or {}
        for cle, prof in d['profils'].items():
            for source, nom, unite in PUBLIEES:
                m = prof['mesures'].get(nom)
                if m:
                    lignes.append([d['id'], d['version'], d['date'], d['methode'], cle, prof['utilisateurs'],
                                   nom, unite, m['mediane'], m['min'], m['max'], m['n'],
                                   prof.get('memoire_a_prevoir_octets'), t.get('vcpu'), t.get('memoire_mio')])
    entete = ['application', 'version', 'date', 'methode', 'profil', 'utilisateurs', 'mesure', 'unite',
              'mediane', 'min', 'max', 'passages', 'memoire_a_prevoir_octets', 'taille_validee_vcpu',
              'taille_validee_memoire_mio']
    for nom, rows in ((app, [l for l in lignes if l[0] == app]), ('toutes', lignes)):
        buf = io.StringIO()
        w = csv.writer(buf, lineterminator='\n')
        w.writerow(entete)
        w.writerows(rows)
        with open(os.path.join(dossier, f'{nom}.csv'), 'w') as f:
            f.write(buf.getvalue())
    with open(os.path.join(dossier, 'toutes.json'), 'w') as f:
        json.dump({'licence': 'CC BY 4.0', 'source': SOURCE, 'applications': toutes},
                  f, indent=1, ensure_ascii=False)
        f.write('\n')

    print(f'{app}: published {len(profils)} profiles, size {taille["vcpu"]} vCPU {taille["memoire_mio"]} MiB, method {METHODE}')


if __name__ == '__main__':
    sys.exit(main())
