// OpenSTA, Static Timing Analyzer
// Copyright (c) 2026, Parallax Software, Inc.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// 
// The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software.
// 
// Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 
// This notice may not be removed or altered from any source distribution.

#pragma once

#include <string>
#include <string_view>

#include "GraphClass.hh"
#include "NetworkClass.hh"
#include "Sdc.hh"
#include "Zlib.hh"

namespace sta {

class WriteSdcObject;

class WriteSdc : public StaState
{
public:
  WriteSdc(const Sdc *sdc,
           Instance *instance,
           std::string_view creator,
           bool map_hpins,
           bool native,
           int digits,
           bool no_timestamp);
  ~WriteSdc() override = default;
  void write(std::string_view filename,
             bool gzip);

  void openFile(std::string_view filename,
                bool gzip);
  void closeFile();
  virtual void writeHeader() const;
  void writeTiming() const;
  void writeDisables() const;
  void writeDisabledCells() const;
  void writeDisabledPorts() const;
  void writeDisabledLibPorts() const;
  void writeDisabledInstances() const;
  void writeDisabledPins() const;
  void writeDisabledEdges() const;
  void writeDisabledEdge(Edge *edge) const;
  void findMatchingEdges(Edge *edge,
                         EdgeSet &matches) const;
  bool edgeSenseIsUnique(Edge *edge,
                         EdgeSet &matches) const;
  void writeDisabledEdgeSense(Edge *edge) const;
  void writeClocks() const;
  void writeClock(Clock *clk) const;
  void writeGeneratedClock(Clock *clk) const;
  void writeClockPins(const Clock *clk) const;
  void writeFloatSeq(const FloatSeq &floats,
                     float scale) const;
  void writeIntSeq(const IntSeq &ints) const;
  void writeClockSlews(const Clock *clk) const;
  void writeClockUncertainty(const Clock *clk) const;
  void writeClockUncertainty(const Clock *clk,
                             std::string_view setup_hold,
                             float value) const;
  void writeClockUncertaintyPins() const;
  void writeClockUncertaintyPin(const Pin *pin,
                                ClockUncertainties *uncertainties) const;
  void writeClockUncertaintyPin(const Pin *pin,
                                std::string_view setup_hold,
                                float value) const;
  void writeClockLatencies() const;
  void writeClockInsertions() const;
  void writeClockInsertion(ClockInsertion *insert,
                           WriteSdcObject &write_obj) const;
  void writeInterClockUncertainties() const;
  void writeInterClockUncertainty(InterClockUncertainty *uncertainty) const;
  void writePropagatedClkPins() const;
  void writeInputDelays() const;
  void writeOutputDelays() const;
  void writePortDelay(PortDelay *port_delay,
                      bool is_input_delay,
                      std::string_view sdc_cmd) const;
  void writePortDelay(PortDelay *port_delay,
                      bool is_input_delay,
                      float delay,
                      const RiseFallBoth *rf,
                      const MinMaxAll *min_max,
                      std::string_view sdc_cmd) const;
  void writeClockSenses() const;
  void writeClockSense(PinClockPair &pin_clk,
                       ClockSense sense) const;
  void writeClockGroups() const;
  void writeClockGroups(ClockGroups *clk_groups) const;
  void writeExceptions() const;
  void writeException(ExceptionPath *exception) const;
  void writeExceptionCmd(ExceptionPath *exception) const;
  void writeExceptionValue(ExceptionPath *exception) const;
  void writeExceptionFrom(ExceptionFrom *from) const;
  void writeExceptionTo(ExceptionTo *to) const;
  void writeExceptionFromTo(ExceptionFromTo *from_to,
                            std::string_view from_to_key,
                            bool map_hpin_to_drvr) const;
  void writeExceptionThru(ExceptionThru *thru) const;
  void mapThruHpins(ExceptionThru *thru,
                    PinSeq &pins) const;
  void writeDataChecks() const;
  void writeDataCheck(DataCheck *check) const;
  void writeDataCheck(DataCheck *check,
                      const RiseFallBoth *from_rf,
                      const RiseFallBoth *to_rf,
                      const SetupHold *setup_hold,
                      float margin) const;
  void writeEnvironment() const;
  void writeOperatingConditions() const;
  void writeWireload() const;
  virtual void writeNetLoads() const;
  void writeNetLoad(const Net *net,
                    const MinMaxAll *min_max,
                    float cap) const;
  void writePortLoads() const;
  void writePortLoads(const Port *port) const;
  void writePortFanout(const Port *port) const;
  void writeDriveResistances() const;
  void writeDrivingCells() const;
  void writeInputTransitions() const;
  void writeDrivingCell(Port *port,
                        InputDriveCell *drive_cell,
                        const RiseFall *rf,
                        const MinMax *min_max) const;
  void writeConstants() const;
  virtual void writeConstant(const Pin *pin) const;
  std::string_view setConstantCmd(const Pin *pin) const;
  void writeCaseAnalysis() const;
  virtual void writeCaseAnalysis(const Pin *pin) const;
  std::string_view caseAnalysisValueStr(const Pin *pin) const;
  void sortedLogicValuePins(const LogicValueMap &value_map,
                            PinSeq &pins) const;
  void writeNetResistances() const;
  void writeNetResistance(const Net *net,
                          const MinMaxAll *min_max,
                          float res) const;
  void writeDesignRules() const;
  void writeMinPulseWidths() const;
  void writeMinPulseWidths(RiseFallValues *min_widths,
                           WriteSdcObject &write_obj) const;
  void writeMinPulseWidth(std::string_view hi_low,
                          float value,
                          WriteSdcObject &write_obj) const;
  void writeSlewLimits() const;
  void writeCapLimits() const;
  void writeCapLimits(const MinMax *min_max,
                      std::string_view cmd) const;
  void writeMaxArea() const;
  void writeFanoutLimits() const;
  void writeFanoutLimits(const MinMax *min_max,
                         std::string_view cmd) const;
  void writeLatchBorowLimits() const;
  void writeDeratings() const;
  void writeDerating(DeratingFactorsGlobal *factors) const;
  void writeDerating(DeratingFactorsCell *factors,
                     WriteSdcObject *write_obj) const;
  void writeDerating(DeratingFactors *factors,
                     TimingDerateType type,
                     const MinMax *early_late,
                     WriteSdcObject *write_obj) const;
  void writeVoltages() const;

  std::string pathName(const Pin *pin) const;
  std::string pathName(const Net *net) const;
  std::string pathName(const Instance *inst) const;
  void writeCommentSection(std::string_view line) const;
  void writeCommentSeparator() const;

  void writeGetTimingArcsOfOjbects(const LibertyCell *cell) const;
  void writeGetTimingArcs(Edge *edge,
                          std::string_view filter = {}) const;
  std::string_view getTimingArcsCmd() const;
  void writeGetLibCell(const LibertyCell *cell) const;
  void writeGetLibPin(const LibertyPort *port) const;
  void writeGetClock(const Clock *clk) const;
  void writeGetClocks(ClockSet *clks) const;
  void writeGetClocks(ClockSet *clks,
                      bool multiple,
                      bool &first) const;
  virtual void writeGetPort(const Port *port) const;
  virtual void writeGetNet(const Net *net) const;
  virtual void writeGetInstance(const Instance *inst) const;
  virtual void writeGetPin(const Pin *pin) const;
  void writeGetPin(const Pin *pin,
                   bool map_hpin_to_drvr) const;
  void writeGetPins(const PinSet *pins,
                    bool map_hpin_to_drvr) const;
  void writeGetPins1(PinSeq *pins) const;
  void writeClockKey(const Clock *clk) const;
  float scaleTime(float time) const;
  float scaleCapacitance(float cap) const;
  float scaleResistance(float res) const;
  void writeFloat(float value) const;
  void writeTime(float time) const;
  void writeCapacitance(float cap) const;
  void writeResistance(float res) const;

  void writeClkSlewLimits() const;
  void writeClkSlewLimit(std::string_view clk_data,
                         std::string_view rise_fall,
                         const Clock *clk,
                         float limit) const;
  void writeRiseFallMinMaxTimeCmd(std::string_view sdc_cmd,
                                  const RiseFallMinMax *values,
                                  WriteSdcObject &write_object) const;
  void writeRiseFallMinMaxCapCmd(std::string_view sdc_cmd,
                                 const RiseFallMinMax *values,
                                 WriteSdcObject &write_object) const;
  void writeRiseFallMinMaxCmd(std::string_view sdc_cmd,
                              const RiseFallMinMax *values,
                              float scale,
                              WriteSdcObject &write_object) const;
  void writeRiseFallMinMaxCmd(std::string_view sdc_cmd,
                              float value,
                              float scale,
                              const RiseFallBoth *rf,
                              const MinMaxAll *min_max,
                              WriteSdcObject &write_object) const;
  void writeMinMaxFloatValuesCmd(std::string_view sdc_cmd,
                                 const MinMaxFloatValues *values,
                                 float scale,
                                 WriteSdcObject &write_object) const;
  void writeMinMaxFloatCmd(std::string_view sdc_cmd,
                           float value,
                           float scale,
                           const MinMaxAll *min_max,
                           WriteSdcObject &write_object) const;
  void writeMinMaxIntValuesCmd(std::string_view sdc_cmd,
                               const MinMaxIntValues *values,
                               WriteSdcObject &write_object) const;
  void writeMinMaxIntCmd(std::string_view sdc_cmd,
                         int value,
                         const MinMaxAll *min_max,
                         WriteSdcObject &write_object) const;
  void writeSetupHoldFlag(const MinMaxAll *min_max) const;
  void writeVariables() const;
  void writeCmdComment(SdcCmdComment *cmd) const;

  gzFile stream() const { return stream_; }

protected:
  const Sdc *sdc_;
  Instance *instance_;
  std::string creator_;
  bool map_hpins_;
  bool native_;
  int digits_;
  bool no_timestamp_;
  bool top_instance_;
  size_t instance_name_length_;
  Cell *cell_;
  gzFile stream_;
};

} // namespace sta
