#!/usr/bin/env python3

import asyncio
import json
import textwrap
from pathlib import Path

from mitmproxy import certs
from mitmproxy.http import Headers
from mitmproxy.test import tflow
from mitmproxy.tools.web import app

here = Path(__file__).parent.absolute()

filename = here / "../src/js/__tests__/ducks/_tflow.ts"


async def make() -> str:
    tf_http = tflow.tflow(resp=True, err=True, ws=True)
    tf_http.id = "d91165be-ca1f-4612-88a9-c0f8696f3e29"
    tf_http.client_conn.id = "4a18d1a0-50a1-48dd-9aa6-d45d74282939"
    tf_http.server_conn.id = "f087e7b2-6d0a-41a8-a8f0-e1a4761395f8"
    tf_http.server_conn.certificate_list = [
        certs.Cert.from_pem(
            (
                here / "../../test/mitmproxy/net/data/verificationcerts/self-signed.pem"
            ).read_bytes()
        )
    ]
    tf_http.request.trailers = Headers(trailer="qvalue")
    tf_http.response.trailers = Headers(trailer="qvalue")
    tf_http.comment = "I'm a comment!"

    tf_tcp = tflow.ttcpflow(err=True)
    tf_tcp.id = "2ea7012b-21b5-4f8f-98cd-d49819954001"
    tf_tcp.client_conn.id = "8be32b99-a0b3-446e-93bc-b29982fe1322"
    tf_tcp.server_conn.id = "e33bb2cd-c07e-4214-9a8e-3a8f85f25200"

    tf_udp = tflow.tudpflow(err=True)
    tf_udp.id = "f9f7b2b9-7727-4477-822d-d3526e5b8951"
    tf_udp.client_conn.id = "0a8833da-88e4-429d-ac54-61cda8a7f91c"
    tf_udp.server_conn.id = "c49f9c2b-a729-4b16-9212-d181717e294b"

    tf_dns = tflow.tdnsflow(resp=True, err=True)
    tf_dns.id = "5434da94-1017-42fa-872d-a189508d48e4"
    tf_dns.client_conn.id = "0b4cc0a3-6acb-4880-81c0-1644084126fc"
    tf_dns.server_conn.id = "db5294af-c008-4098-a320-a94f901eaf2f"

    # language=TypeScript
    content = (
        "/** Auto-generated by web/gen/tflow_js.py */\n"
        "import type {HTTPFlow, TCPFlow, UDPFlow, DNSFlow} from '../../flow';\n"
        "export function THTTPFlow(): Required<HTTPFlow> {\n"
        "    return %s\n"
        "}\n"
        "export function TTCPFlow(): Required<TCPFlow> {\n"
        "    return %s\n"
        "}\n"
        "export function TUDPFlow(): Required<UDPFlow> {\n"
        "    return %s\n"
        "}\n"
        "export function TDNSFlow(): Required<DNSFlow> {\n"
        "    return %s\n"
        "}\n"
        % (
            textwrap.indent(
                json.dumps(app.flow_to_json(tf_http), indent=4, sort_keys=True), "    "
            ),
            textwrap.indent(
                json.dumps(app.flow_to_json(tf_tcp), indent=4, sort_keys=True), "    "
            ),
            textwrap.indent(
                json.dumps(app.flow_to_json(tf_udp), indent=4, sort_keys=True), "    "
            ),
            textwrap.indent(
                json.dumps(app.flow_to_json(tf_dns), indent=4, sort_keys=True), "    "
            ),
        )
    )
    content = content.replace(": null", ": undefined")
    return content


if __name__ == "__main__":
    filename.write_bytes(asyncio.run(make()).encode())
