#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Simafri measured requirements bench: from the analysis of a campaign to the published data.
#
#   publier.py --analyse results.json --fiche apps/<app>/fiche.json --paliers tiers.json \
#              --date YYYY-MM-DD --site <simafri-web checkout>
#
# Writes, in the site checkout:
#   - src/data/configurations/apps/<app>.js  the facts the pages read (never typed by hand);
#   - public/donnees/configurations/<app>.json and <app>.csv, the open data of the application;
#   - public/donnees/configurations/toutes.json and toutes.csv, every application together.
# Refuses to write a profile whose runs did not all hold, or whose tier 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.0'

# 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_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'),
]


def arrondi(v, unite):
    if v is None:
        return None
    if unite == 'octets' or unite == 'octets_par_seconde':
        return int(round(v))
    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 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('--paliers', required=True)
    p.add_argument('--date', required=True, help='day of the campaign, YYYY-MM-DD')
    p.add_argument('--parution', required=True, help="publication slot of the site's pages: YYYY-MM-DD, or with T09:00:00Z or T12:00:00Z")
    p.add_argument('--site', required=True)
    args = p.parse_args()

    analyse = json.load(open(args.analyse))
    fiche = json.load(open(args.fiche))
    paliers = {t['code']: t for t in json.load(open(args.paliers))}
    app = fiche['id']

    profils = {}
    meta_banc = None
    images = None
    installation = {'reponse_saine_s': [], 'pic': [], '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 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['ecarts_a_rejouer']:
            sys.exit(f'{cle}: spread above 10 % on {prof["ecarts_a_rejouer"]}, replay first')
        passages = prof['passages']
        meta_banc = meta_banc or passages[0]['meta']
        images = images or passages[0]['images']
        candidat = prof['candidat']['palier']
        validations = [v for v in analyse['validations']
                       if v['meta']['profil'] == cle and v['meta']['vcpu'] == candidat['vcpu']
                       and v['meta']['memoire_mio'] == candidat['ram_gio'] * 1024]
        if not validations or not all(v['tenu'] for v in validations):
            sys.exit(f'{cle}: tier {candidat["nom"]} not validated by a replay')
        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)},
            'palier': {'code': candidat['code'], 'nom': candidat['nom'], 'vcpu': candidat['vcpu'],
                       'ram_gio': candidat['ram_gio'], 'valide': True,
                       'validation': {'passages': len(validations),
                                      'dossiers': [v['dossier'] for v in validations]}},
        }
        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['donnees'] += [x['meta']['taille_installee'] for x in passages]
        if a.get('croissance_disque_par_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')

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

    faits = {
        'id': app, 'nom': fiche['nom'], 'categorie': fiche['categorie'], 'site': fiche['site'],
        'depot': fiche['depot'], 'licence': 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': {k: (round(v, 3) if k != 'n' else v) for k, v in stat(installation['reponse_saine_s']).items()},
                         'pic_memoire_travail': {k: int(v) for k, v in stat(installation['pic']).items()},
                         'donnees_octets': {k: int(v) for k, v in stat(installation['donnees']).items()}},
        'croissance_disque_par_1000': croissance,
        'profils': profils,
        'documentation': fiche['documentation'],
    }

    site = args.site
    os.makedirs(os.path.join(site, 'public/donnees/configurations'), exist_ok=True)
    with open(os.path.join(site, f'src/data/configurations/apps/{app}.js'), 'w') as f:
        f.write('// Écrit par public/banc/publier.py depuis l\'analyse de la campagne : jamais retapé à la main.\n')
        f.write('// Rejouer la campagne, puis publier.py, pour le changer.\n')
        f.write(f'export const MESURE = {json.dumps(faits, indent=1, ensure_ascii=False)};\n')
    with open(os.path.join(site, f'public/donnees/configurations/{app}.json'), 'w') as f:
        json.dump({'licence': 'CC BY 4.0', 'source': 'Simafri, https://www.simafri.com/', **faits}, f, indent=1, ensure_ascii=False)
        f.write('\n')

    # Every application together, from the JSON files already published.
    toutes = []
    for path in sorted(glob.glob(os.path.join(site, 'public/donnees/configurations/*.json'))):
        if os.path.basename(path) != 'toutes.json':
            toutes.append(json.load(open(path)))
    lignes = []
    for d in toutes:
        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['palier']['code']])
    entete = ['application', 'version', 'date', 'methode', 'profil', 'utilisateurs', 'mesure', 'unite',
              'mediane', 'min', 'max', 'passages', 'palier_valide']
    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(site, f'public/donnees/configurations/{nom}.csv'), 'w') as f:
            f.write(buf.getvalue())
    with open(os.path.join(site, 'public/donnees/configurations/toutes.json'), 'w') as f:
        json.dump({'licence': 'CC BY 4.0', 'source': 'Simafri, https://www.simafri.com/', 'applications': toutes},
                  f, indent=1, ensure_ascii=False)
        f.write('\n')

    # The canonical of each data file, in the block of public/_headers kept between two marks:
    # the data of an application points to its English page, the file of all of them to the hub.
    headers = os.path.join(site, 'public/_headers')
    texte = open(headers).read()
    debut, fin = '# >>> configurations-mesurees\n', '# <<< configurations-mesurees\n'
    if debut not in texte or fin not in texte:
        sys.exit('public/_headers: the configurations-mesurees block is missing')
    regles = ['/donnees/configurations/toutes.*\n  Link: <https://www.simafri.com/en/requirements/>; rel="canonical"\n']
    for d in toutes:
        regles.append(f'/donnees/configurations/{d["id"]}.*\n  Link: <https://www.simafri.com/en/requirements/{d["id"]}/>; rel="canonical"\n')
    avant, reste = texte.split(debut, 1)
    _, apres = reste.split(fin, 1)
    with open(headers, 'w') as f:
        f.write(avant + debut + ''.join(regles) + fin + apres)
    print(f'{app}: published {len(profils)} profiles')


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