#!/usr/bin/env python

import argparse
import json
import os
from sh import (gnuplot, tar, rm)
from collections import defaultdict
from pathlib import Path

from gobekli.logging import m
from gobekli.chaos.analysis import (make_overview_chart, make_latency_chart,
                                    make_pdf_latency_chart, make_availability_chart,
                                    analyze_inject_recover_availability, LatencyType)

from os import path
import json
import jinja2

INDEX = """
<html>
    <head>
        <title>{{title}}</title>
        <style>
            table.availability {
                border-collapse: collapse;
                border: 1px solid black;
            }

            .availability th {
                border: 1px solid black;
                padding: 0.2em;
            }

            .availability .fault {
                vertical-align: top;
                text-align: left;
            }

            .availability td {
                text-align: right;
                border: 1px solid black;
                padding: 0.2em;
            }

            table.consistency {
                border-collapse: collapse;
                border: 1px solid black;
            }

            .consistency th {
                border: 1px solid black;
                padding: 0.2em;
            }

            .consistency .fault {
                vertical-align: top;
                text-align: left;
            }

            .consistency td {
                text-align: right;
                border: 1px solid black;
                padding: 0.2em;
            }
        </style>
    </head>
    <body>
        <table class="setup">
            <tr>
                <td class="label">system</td>
                <td class="value">{{ system }}</td>
            </tr>
            <tr>
                <td class="label">workload</td>
                <td class="value">{{ workload }}</td>
            </tr>
            <tr>
                <td class="label">scenario</td>
                <td class="value">{{ scenario }}</td>
            </tr>
        </table>

        <h1>Consistency</h1>
        
        <table class="consistency">
            <thead>
                <tr>
                    <th>Fault</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
{% for ctest in ctests %}
                <tr>
                    <th class="fault" rowspan="{{ ctest.span }}">{{ ctest.fault }}</th>
{% if ctest.first.is_err %}
                    <td class="failed">{{ ctest.first.error }} (<a href="{{ ctest.first.logs }}">cmd logs</a>)</td>
{% else %}
                    <td class="passed">{{ ctest.first.status }}</td>
{% endif %}
                </tr>
{% for ctest in ctest.rest %}
                <tr>
                    <td class="failed">{{ ctest.error }} (<a href="{{ ctest.logs }}">cmd logs</a>)</td>
                </tr>
{% endfor %}
{% endfor %}
            </tbody>
        </table>

        <h1>Availability</h1>

        <table class="availability">
            <thead>
                <tr>
                    <th>Fault</th>
                    <th>id</th>
                    <th>min latency</th>
                    <th>p99 latency</th>
                    <th>max-1 latency</th>
                    <th>max latency</th>
                    <th>max unavailability</th>
                </tr>
            </thead>
            <tbody>
{% for atest in atests %}
                <tr>
                    <th class="fault" rowspan="{{ atest.span }}">{{ atest.fault }}</th>
                    <th>
                        <a href="{{ atest.first.link }}">
                            {{ atest.first.id }}
                        </a>
                    </th>
                    <td>{{ "{:,}".format(atest.first.min_lat) }}</td>
                    <td>{{ "{:,}".format(atest.first.p99_lat) }}</td>
                    <td>{{ "{:,}".format(atest.first.second_max_lat) }}</td>
                    <td>{{ "{:,}".format(atest.first.max_lat) }}</td>
                    <td>{{ "{:,}".format(atest.first.max_unavailability) }}</td>
                </tr>
{% for atest in atest.rest %}
                <tr>
                    <th>
                        <a href="{{ atest.link }}">
                            {{ atest.id }}
                        </a>
                    </th>
                    <td>{{ "{:,}".format(atest.min_lat) }}</td>
                    <td>{{ "{:,}".format(atest.p99_lat) }}</td>
                    <td>{{ "{:,}".format(atest.second_max_lat) }}</td>
                    <td>{{ "{:,}".format(atest.max_lat) }}</td>
                    <td>{{ "{:,}".format(atest.max_unavailability) }}</td>
                </tr>
{% endfor %}
{% endfor %}
            </tbody>
        </table>

    </body>
</html>
"""

EXPERIMENT = """
<html>
    <head>
        <script>
            function show_hide(visible_id, hidden_id) {
                const visible = document.getElementById(visible_id);
                visible.style.display = "block";
                const hidden = document.getElementById(hidden_id);
                hidden.style.display = "none";
            }
        </script>
        <style>
            .a {
                text-decoration: underline;
                cursor: pointer;
            }
        </style>
    </head>
    <body>
        <table class="setup">
            <tr>
                <td class="label">system</td>
                <td class="value">{{ system }}</td>
            </tr>
            <tr>
                <td class="label">workload</td>
                <td class="value">{{ workload }}</td>
            </tr>
            <tr>
                <td class="label">scenario</td>
                <td class="value">{{ scenario }}</td>
            </tr>
            <tr>
                <td class="label">fault</td>
                <td class="value">{{ fault }}</td>
            </tr>
            <tr>
                <td class="label">id</td>
                <td class="value">{{ id }}</td>
            </tr>
            <tr>
                <td class="label">min latecy</td>
                <td class="value">{{ min_lat }}</td>
            </tr>
            <tr>
                <td class="label">max latecy</td>
                <td class="value">{{ max_lat }}</td>
            </tr>
            <tr>
                <td class="label">max unavailabilityva</td>
                <td class="value">{{ max_unavailability }}</td>
            </tr>
        </table>

{% for chart in charts %}
        <div>
            <h2>{{ chart.title }}</h2>

            <div id="{{ chart.id }}_overall">
            <h3>Overall <span class="a" onclick="show_hide('{{ chart.id }}_producer','{{ chart.id }}_overall')">Producer</span></h3>

            <a href="{{ chart.latency_overall }}"><img src="{{ chart.latency_overall }}" width="600"/></a>

            <a href="{{ chart.pdf_latency_overall }}"><img src="{{ chart.pdf_latency_overall }}" width="600"/></a>

            <a href="{{ chart.availability }}"><img src="{{ chart.availability }}" width="600"/></a>        
            </div>

            <div id="{{ chart.id }}_producer" style="display: none;">
            <h3><span class="a" onclick="show_hide('{{ chart.id }}_overall','{{ chart.id }}_producer')">Overall</span> Producer</h3>

            <a href="{{ chart.latency_producer }}"><img src="{{ chart.latency_producer }}" width="600"/></a>

            <a href="{{ chart.pdf_latency_producer }}"><img src="{{ chart.pdf_latency_producer }}" width="600"/></a>

            <a href="{{ chart.availability }}"><img src="{{ chart.availability }}" width="600"/></a>        
            </div>
        </div>
{% endfor %}
    </body>
</html>
"""

def build_charts(config, root, results, warmup_s, zoom_us):
    for result in results:
        path = os.path.join(root, result["path"])
        make_overview_chart(result["title"], path, result["availability_log"], result["latency_log"], warmup_s, LatencyType.OVERALL)
        make_overview_chart(result["title"], path, result["availability_log"], result["latency_log"], warmup_s, LatencyType.PRODUCER)
        make_availability_chart(result["title"], None, path, result["availability_log"], result["latency_log"], warmup_s)
        for endpoint in config["endpoints"]:
           make_availability_chart(result["title"], endpoint["idx"], path, result["availability_log"], result["latency_log"], warmup_s)
        make_pdf_latency_chart(result["title"], None, path, result["availability_log"], result["latency_log"], warmup_s, zoom_us, LatencyType.OVERALL)
        make_pdf_latency_chart(result["title"], None, path, result["availability_log"], result["latency_log"], warmup_s, zoom_us, LatencyType.PRODUCER)
        for endpoint in config["endpoints"]:
            make_pdf_latency_chart(result["title"], endpoint["idx"], path, result["availability_log"], result["latency_log"], warmup_s, zoom_us, LatencyType.OVERALL)
            make_pdf_latency_chart(result["title"], endpoint["idx"], path, result["availability_log"], result["latency_log"], warmup_s, zoom_us, LatencyType.PRODUCER)
        for endpoint in config["endpoints"]:
            make_latency_chart(result["title"], endpoint["idx"], path, result["availability_log"], result["latency_log"], warmup_s, LatencyType.OVERALL)
            make_latency_chart(result["title"], endpoint["idx"], path, result["availability_log"], result["latency_log"], warmup_s, LatencyType.PRODUCER)
        came_from = os.getcwd()
        os.chdir(path)
        gnuplot("pdf.latency.overall.all.gp")
        rm("pdf.latency.overall.all.gp")
        rm("pdf.latency.overall.all.log")
        gnuplot("pdf.latency.producer.all.gp")
        rm("pdf.latency.producer.all.gp")
        rm("pdf.latency.producer.all.log")
        for endpoint in config["endpoints"]:
            idx = endpoint["idx"]
            gnuplot(f"pdf.latency.overall.{idx}.gp")
            rm(f"pdf.latency.overall.{idx}.gp")
            rm(f"pdf.latency.overall.{idx}.log")
            gnuplot(f"pdf.latency.producer.{idx}.gp")
            rm(f"pdf.latency.producer.{idx}.gp")
            rm(f"pdf.latency.producer.{idx}.log")
        
        gnuplot("availability.all.gp")
        rm("availability.all.gp")
        rm("availability.all.log")
        for endpoint in config["endpoints"]:
            idx = endpoint["idx"]
            gnuplot(f"availability.{idx}.gp")
            rm(f"availability.{idx}.gp")
            rm(f"availability.{idx}.log")

        for endpoint in config["endpoints"]:
            idx = endpoint["idx"]
            gnuplot(f"latency.overall.{idx}.gp")
            rm(f"latency.overall.{idx}.gp")
            rm(f"latency.overall.{idx}.log")
            gnuplot(f"latency.producer.{idx}.gp")
            rm(f"latency.producer.{idx}.gp")
            rm(f"latency.producer.{idx}.log")

        gnuplot("overview.overall.gp")
        rm("overview.overall.gp")
        rm("overview.lat.overall.log")

        gnuplot("overview.producer.gp")
        rm("overview.producer.gp")
        rm("overview.lat.producer.log")
        rm("overview.1s.log")

        os.chdir(came_from)

def archive_logs(root, results):
    logs = []
    for result in results:
        for f in os.listdir(path.join(root, result["path"])):
            if f.endswith(".log"):
                logs.append(path.join(root, result["path"], f))
    tar_args = ["cjf", path.join(root, "logs.tar.bz2")] + logs
    tar(*tar_args)
    for f in logs:
        os.remove(f)

def archive_failed_cmd_log(root, results):
    for result in results:
        status = result["status"] # passed | failed
        if status == "passed":
            for f in os.listdir(path.join(root, result["path"])):
                if f.startswith(result["cmd_log"]):
                    os.remove(path.join(root, result["path"], f))
        else:
            cmd_logs = []
            for f in os.listdir(path.join(root, result["path"])):
                if f.startswith(result["cmd_log"]) and not f.endswith(".tar.bz2"):
                    cmd_logs.append(f)
            if len(cmd_logs) > 0:
                tar_args = ["cjf", result["cmd_log"] + ".tar.bz2"] + cmd_logs
                came_from = os.getcwd()
                os.chdir(os.path.join(root, result["path"]))
                tar(*tar_args)
                os.chdir(came_from)
                for f in cmd_logs:
                    os.remove(path.join(root, result["path"], f))


class ChartSet:
    def __init__(self, id, title, latency_overall, latency_producer, pdf_latency_overall, pdf_latency_producer, availability):
        self.title = title
        self.id = id
        self.latency_overall = latency_overall
        self.latency_producer = latency_producer
        self.pdf_latency_overall = pdf_latency_overall
        self.pdf_latency_producer = pdf_latency_producer
        self.availability = availability

def build_experiment_index(context, config, root, result, warmup, zoom_us):
    index_path = os.path.join(root, result["path"], "index.html")
    
    charts = []

    if len(config["endpoints"]) > 1:
        charts.append(
            ChartSet("overview", "Combined", "overview.overall.png", "overview.producer.png", "pdf.latency.overall.all.png", "pdf.latency.producer.all.png", "availability.all.png")
        )

    for endpoint in config["endpoints"]:
        idx = endpoint["idx"]
        charts.append(
            ChartSet(endpoint["id"], endpoint["id"], f"latency.overall.{idx}.png", f"latency.producer.{idx}.png", f"pdf.latency.overall.{idx}.png", f"pdf.latency.producer.{idx}.png", f"availability.{idx}.png")
        )
        

    
    with open(index_path, 'w') as html:
        html.write(jinja2.Template(EXPERIMENT).render(
            system = context["system"],
            workload = context["workload"],
            scenario = context["scenario"],
            charts = charts,
            fault = result["fault"],
            id = result["id"],
            min_lat = result["stat"]["min_lat"],
            max_lat = result["stat"]["max_lat"],
            max_unavailability =  result["stat"]["max_unavailability"]
        ))

def load_results(context, results_log, warmup_s):
    root = Path(results_log).parent
    with open(results_log) as result_file:
        for line in result_file:
            result = json.loads(line)
            result["stat"] = analyze_inject_recover_availability(
                path.join(root, result["path"]),
                result["availability_log"],
                result["latency_log"],
                warmup_s
            )
            yield result

def load_context(root):
    with open(path.join(root, "context.json")) as context_info:
        return json.load(context_info)

def build_alerts(root, results):
    with open(path.join(root, "alerts.log"), "w") as alerts:
        for result in results:
            if result["status"] == "failed":
                alerts.write(str(m(type="consistency", message=result["error"], id=result["id"])) + "\n")

def load_config(root):
    with open(path.join(root, "settings.json")) as config_json:
        return json.load(config_json)

def build_index(context, title, root, results):
    ava_stat = defaultdict(lambda: [])
    fault_stat = defaultdict(lambda: { "passed": 0, "failed": [] })
    
    for result in results:
        fault = result["fault"]
        status = result["status"] # passed | failed
        if status == "passed":
            fault_stat[fault]["passed"] += 1
        else:
            fault_stat[fault]["failed"].append({
                "error": result["error"],
                "status": "failed",
                "logs": path.join(result["path"], result["cmd_log"] + ".tar.bz2"),
                "is_err": True
            })

    for result in results:
        availability = result["stat"]
        availability["id"] = result["id"]
        availability["link"] = os.path.join(result["path"], "index.html")
        ava_stat[result["fault"]].append(availability)
    
    atests = []
    for fault in ava_stat.keys():
        stat = ava_stat[fault]
        atests.append({
            "fault": fault, "span": len(stat),
            "first": stat[0], "rest": stat[1:]
        })

    ctests = []
    for fault in fault_stat.keys():
        first = None
        rest = []

        if fault_stat[fault]["passed"] > 0:
            first = {
                "status": "passed(" + str(fault_stat[fault]["passed"]) + ")",
                "is_err": False
            }
            rest = fault_stat[fault]["failed"]
        else:
            first = fault_stat[fault]["failed"][0]
            rest = fault_stat[fault]["failed"][1:]

        ctests.append({"fault": fault, "span": 1 + len(rest), "first": first, "rest": rest})

    with open(path.join(root, "index.html"), 'w') as html:
        html.write(jinja2.Template(INDEX).render(
            title = title,
            system = context["system"],
            workload = context["workload"],
            scenario = context["scenario"],
            ctests = ctests,
            atests = atests
        ))

def build_report(results_log, warmup_s, zoom_us):
    root = Path(results_log).parent
    context = load_context(root)
    config = load_config(root)
    results = list(load_results(context, results_log, warmup_s))   

    build_charts(config, root, results, warmup_s, zoom_us)
    archive_failed_cmd_log(root, results)
    
    for result in results:
        build_experiment_index(context, config, root, result, warmup_s, zoom_us)
    
    build_index(context, results_log, root, results)
    build_alerts(root, results)
    archive_logs(root, results)

parser = argparse.ArgumentParser(description='build gobekli report')
parser.add_argument('--result', action='append', required=True)
parser.add_argument('--warmup_s', type=int, default=5, required=False)
parser.add_argument('--zoom_us', type=int, default=100000, required=False)

args = parser.parse_args()
for result in args.result:
    build_report(result, args.warmup_s, args.zoom_us)