{{ header }}
# PCILeech Synthesis Script
puts "Configuring synthesis settings..."
set_property strategy "Vivado Synthesis Defaults" [get_runs synth_1]
set_property steps.synth_design.args.directive "AreaOptimized_high" [get_runs synth_1]

puts "Starting synthesis..."
reset_run synth_1
launch_runs synth_1 -jobs 8
wait_on_run synth_1

if {[get_property PROGRESS [get_runs synth_1]] != "100%"} {
    puts "ERROR: Synthesis failed!"
    exit 1
}

open_run synth_1
report_utilization -file utilization_synth.rpt

# -------------------------------------------------------------------------
# Early resource-compatibility check after synthesis
# -------------------------------------------------------------------------
# Check if synthesis results would fit on target devices before implementation

array set CAP_LUTs  {35t 20800  75t 46560}
array set CAP_REGs  {35t 41600  75t 93120}
array set CAP_BRAMS {35t  50    75t   135}
array set CAP_DSPS  {35t  90    75t   180}

# Determine target part
set part    [get_property PART [current_project]]
set partkey [expr {[string match -nocase *35t* $part] ? "35t" : \
                   ([string match -nocase *75t* $part] ? "75t" : "75t")}]

# Get synthesis utilization
set u_str [report_utilization -return_string -quiet]

{% raw %}proc parse_synth_field {field txt} {
    regexp [format {%s\s+\|\s+(\d+)} [string map {[ \\[ ] \\]} $field]] $txt -> val
    return $val
}

set usedLUT [parse_synth_field "CLB LUTs"       $u_str]
set usedREG [parse_synth_field "CLB Registers"  $u_str]
set usedBR  [parse_synth_field "Block RAM Tile" $u_str]
set usedDSP [parse_synth_field "DSPs"           $u_str]{% endraw %}

# Check against 35T limits (early warning)
{% raw %}foreach {capName used arr} {
    LUTs        $usedLUT CAP_LUTs
    Registers   $usedREG CAP_REGs
    BRAMs       $usedBR  CAP_BRAMS
    DSPs        $usedDSP CAP_DSPS
} {
    set max35 [set ${arr}(35t)]
    if {$used > $max35} {
        puts "WARNING: Post-synthesis design uses $used $capName but 35T card only has $max35"
        puts "         Implementation may increase usage further - build may fail"
    }
}{% endraw %}

puts "Synthesis completed successfully"