# sta.tcl - OpenSTA timing and power analysis script
# Read liberty (may be space-delimited for multi-lib PDKs)
foreach _lib $::env(LIBERTY_FILE) {
    read_liberty $_lib
}

# Read netlist
read_verilog $::env(NETLIST_FILE)
link_design $::env(TOP_MODULE)

# TODO(drew): support if $::env(STA_SDC_FILE) exists, use that instead

# Create clock
create_clock -period $::env(CLOCK_NS) [get_ports $::env(CLOCK_NAME)]

# Set input/output delays
set_input_delay -clock [get_clocks] $::env(IDELAY_NS) [all_inputs]
set_output_delay -clock [get_clocks] $::env(ODELAY_NS) [all_outputs]

# Report timing
group_path -name reg2reg -from [all_registers] -to [all_registers]
group_path -name in2reg -from [all_inputs] -to [all_registers]
group_path -name reg2out -from [all_registers] -to [all_outputs]
group_path -name in2out -from [all_inputs] -to [all_outputs]

report_checks -path_delay min_max -format full_clock_expanded

# ============================================================================
# Power Analysis
# ============================================================================
puts "\n=========================================="
puts "Power Analysis"
puts "=========================================="
report_power -digits 4

# ============================================================================
# Dump timing report for post-processing
# ============================================================================

puts "\n=========================================="
puts "Generating timing report for analysis..."
puts "=========================================="

# Get FILE_SUFFIX from environment for unique filenames (prevents clobbering in parallel runs)
if {[info exists ::env(FILE_SUFFIX)] && $::env(FILE_SUFFIX) ne ""} {
    set file_suffix $::env(FILE_SUFFIX)
} else {
    set file_suffix "default"
}

# Generate unique timing report filenames
set timing_report_file "$::env(OUT_DIR)/timing_report_${file_suffix}.txt"
set timing_report_file_pipe "$::env(OUT_DIR)/timing_report_pipe_${file_suffix}.txt"

# Redirect report_checks output to file
# Use OpenSTA-compatible syntax
report_checks \
    -slack_max 1e30 \
    -format end \
    -digits 4 \
    -no_line_splits \
    -path_delay max \
    -group_path_count 1000000 \
    > $timing_report_file

report_checks \
    -slack_max 1e30 \
    -format end \
    -path_group reg2reg \
    -digits 4 \
    -no_line_splits \
    -path_delay max \
    -group_path_count 1000000 \
    > $timing_report_file_pipe

puts "Timing report written to: $timing_report_file and $timing_report_file_pipe"
puts "Run process_timing_metrics.py to generate CSV metrics"
puts "=========================================="
