# Copyright (c) 2020, Xilinx
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of FINN nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Vivado-related utility functions for FINN.

This module provides utilities for working with Xilinx Vivado, including
out-of-context synthesis, project creation, and other Vivado-related operations.
"""

import os
from pathlib import Path

from finn.util.basic import launch_process_helper, which
from finn.util.exception import FINNUserError
from finn.util.logging import log


def out_of_context_synth(
    verilog_dir: str | Path,
    top_name: str,
    float_ip_tcl: list[str],
    fpga_part: str = "xczu3eg-sbva484-1-e",
    clk_name: str = "ap_clk_0",
    clk_period_ns: float = 5.0,
    post_synth_verilog: bool = False,
) -> dict[str, str | float]:
    """Run out-of-context Vivado synthesis, return resources and slack."""
    # ensure that vivado is in PATH: source VIVADO_INSTALLATION/settings64.sh
    if which("vivado") is None:
        raise FINNUserError("vivado is not in PATH, ensure settings64.sh is sourced.")

    file_dir = Path(__file__).parent.resolve()
    script_path = file_dir / "vivado_scripts" / "vivadocompile.sh"
    # vivadocompile.sh <top-level-entity> <clock-name (optional)> <fpga-part (optional)>
    flag_post_synth_verilog = 0 if post_synth_verilog else 1
    float_ip_string = '"{}"'.format("#".join(float_ip_tcl))
    call = (
        f"{script_path} {top_name} {float_ip_string} {clk_name} {fpga_part} {float(clk_period_ns)}"
        f"{flag_post_synth_verilog}"
    )
    call = call.split()
    launch_process_helper(call, proc_env=os.environ.copy(), cwd=verilog_dir)

    vivado_proj_folder = f"{verilog_dir}/results_{top_name}"
    res_counts_path = f"{vivado_proj_folder}/res.txt"

    with Path(res_counts_path).open() as myfile:
        res_data = myfile.read().split("\n")
    ret = {}
    ret["vivado_proj_folder"] = vivado_proj_folder
    for res_line in res_data:
        res_fields = res_line.split("=")
        log.info(res_fields)
        try:
            ret[res_fields[0]] = float(res_fields[1])
        except ValueError:
            ret[res_fields[0]] = 0
        except IndexError:
            ret[res_fields[0]] = 0
    if ret["WNS"] == 0:
        ret["fmax_mhz"] = 0
    else:
        ret["fmax_mhz"] = 1000.0 / (clk_period_ns - ret["WNS"])
    return ret
