"""Vivado synthesis backend -- the `full` mode.

The authoritative numbers, and the slow ones. Vivado runs in batch against a
generated Tcl script, produces real utilization and timing reports for the
target part, and takes minutes, which is why this op is marked `long_running`
and goes through the daemon's job path instead of blocking a tool call.

Vivado is not installed on every machine that runs the rest of this toolchain,
and that is fine: the backend declares `requires="vivado"`, so an agent gets a
clear `backend_unavailable` rather than a confusing crash, and `estimate` keeps
working.
"""

from __future__ import annotations

import re

from ...process import run as run_process
from ...registry import backend
from . import SynthIn, SynthOut, Timing, Utilization

TCL = """\
# Generated by ic synth --mode full. Regenerate rather than edit.
create_project -in_memory -part {part}
{reads}
set_property top {top} [current_fileset]
synth_design -top {top} -part {part}
report_utilization -file {util_report}
report_timing_summary -file {timing_report}
"""

UTIL_ROW = re.compile(r"^\|\s*(?P<name>[\w \-\.]+?)\s*\|[^|]*\|\s*(?P<used>\d+)\s*\|")
WNS = re.compile(r"WNS\(ns\)\s*.*?\n[-\s|]*\n\s*(?P<wns>-?\d+\.\d+)\s+(?P<tns>-?\d+\.\d+)", re.S)


def parse_utilization(text: str) -> Utilization:
    """Read Vivado's utilization table.

    The table names resources per device family, so several spellings map to
    each field; anything unrecognised is ignored rather than guessed at.
    """
    values: dict[str, int] = {}
    for line in text.splitlines():
        match = UTIL_ROW.match(line.strip())
        if match:
            values[match.group("name").strip().lower()] = int(match.group("used"))

    def pick(*names) -> int | None:
        for name in names:
            if name in values:
                return values[name]
        return None

    return Utilization(
        luts=pick("slice luts", "clb luts", "slice luts*"),
        ffs=pick("slice registers", "clb registers", "register as flip flop"),
        dsps=pick("dsps", "dsp48e1s", "dsps*"),
        brams=pick("block ram tile", "block ram tile*"),
        cells=None,
        memory_bits=None,
    )


def parse_timing(text: str) -> Timing:
    match = WNS.search(text)
    if not match:
        return Timing(met=None)
    wns = float(match.group("wns"))
    return Timing(wns_ns=wns, tns_ns=float(match.group("tns")), met=wns >= 0)


@backend("synth", "vivado", requires="vivado", version_cmd=["vivado", "-version"])
class VivadoSynth:
    def synth(self, params: SynthIn, ctx) -> SynthOut:
        work = ctx.run.work
        util_report = ctx.run.artifacts / "utilization.rpt"
        timing_report = ctx.run.artifacts / "timing.rpt"

        reads = []
        for directory in params.include_dirs:
            reads.append(f"set_property include_dirs {{{directory}}} [current_fileset]")
        for define in params.defines:
            reads.append(f"set_property verilog_define {{{define}}} [current_fileset]")
        for source in params.files:
            reads.append(f"read_verilog -sv {{{source}}}")

        script = work / "synth.tcl"
        script.write_text(
            TCL.format(
                part=params.part,
                top=params.top,
                reads="\n".join(reads),
                util_report=util_report,
                timing_report=timing_report,
            )
        )

        log = ctx.run.artifacts / "synth.log"
        result = run_process(
            ["vivado", "-mode", "batch", "-nojournal", "-notrace",
             "-log", str(work / "vivado.log"), "-source", str(script)],
            log_path=log,
            cwd=work,
            timeout_s=params.timeout_s,
        )

        utilization = parse_utilization(
            util_report.read_text(errors="replace") if util_report.exists() else ""
        )
        timing = parse_timing(
            timing_report.read_text(errors="replace") if timing_report.exists() else ""
        )
        text = result.text()
        summary = [ln.strip() for ln in text.splitlines()
                   if ln.startswith(("ERROR:", "CRITICAL WARNING:"))][:8]
        if not summary and timing.wns_ns is not None:
            summary = [f"WNS {timing.wns_ns} ns, TNS {timing.tns_ns} ns"]

        return SynthOut(
            ok=result.exit_code == 0 and not result.timed_out,
            mode="full",
            top=params.top,
            part=params.part,
            utilization=utilization,
            timing=timing,
            summary=summary,
            report=ctx.run.handle("synth.log"),
            exit_code=result.exit_code,
            duration_s=round(result.duration_s, 3),
            backend="vivado",
            backend_version=ctx.backend_version,
            note="Authoritative for this part. Bitstream generation is a separate step.",
        )
