// IR 文本输出：
// - 将 IR 打印为 .ll 风格的文本
// - 支撑调试与测试对比（diff）

#include "ir/IR.h"

#include <ostream>
#include <stdexcept>
#include <string>

#include "utils/Log.h"

namespace ir {

static const char* TypeToString(const Type& ty) {
  switch (ty.GetKind()) {
    case Type::Kind::Void:
      return "void";
    case Type::Kind::Int32:
      return "i32";
    case Type::Kind::Float32:
      return "float";
    case Type::Kind::Pointer:
      return "i32*";  // 目前仅支持 i32* 指针打印
    case Type::Kind::Array:
      return "[array]";
    case Type::Kind::Function:
      return "[function]";
    case Type::Kind::Label:
      return "label";
  }
  throw std::runtime_error(FormatError("ir", "未知类型"));
}

static const char* OpcodeToString(Opcode op) {
  switch (op) {
    case Opcode::Add: return "add";
    case Opcode::Sub: return "sub";
    case Opcode::Mul: return "mul";
    case Opcode::Div: return "sdiv";
    case Opcode::Mod: return "srem";
    case Opcode::And: return "and";
    case Opcode::Or: return "or";
    case Opcode::Xor: return "xor";
    case Opcode::Shl: return "shl";
    case Opcode::LShr: return "lshr";
    case Opcode::AShr: return "ashr";
    case Opcode::ICmp: return "icmp";
    case Opcode::FCmp: return "fcmp";
    case Opcode::Alloca: return "alloca";
    case Opcode::Load: return "load";
    case Opcode::Store: return "store";
    case Opcode::Ret: return "ret";
    case Opcode::Br: return "br";
    case Opcode::CondBr: return "br";
    case Opcode::Call: return "call";
    case Opcode::GEP: return "getelementptr";
    case Opcode::Phi: return "phi";
  }
  return "?";
}

static std::string ValueToString(const Value* v) {
  if (auto* ci = dynamic_cast<const ConstantInt*>(v)) {
    return std::to_string(ci->GetValue());
  }
  return v ? v->GetName() : "<null>";
}

void IRPrinter::Print(const Module& module, std::ostream& os) {
  for (const auto& func : module.GetFunctions()) {
    os << "define " << TypeToString(*func->GetType()) << " @" << func->GetName()
       << "() {\n";
    for (const auto& bb : func->GetBlocks()) {
      if (!bb) {
        continue;
      }
      os << bb->GetName() << ":\n";
      for (const auto& instPtr : bb->GetInstructions()) {
        const auto* inst = instPtr.get();
        switch (inst->GetOpcode()) {
          case Opcode::Add:
          case Opcode::Sub:
          case Opcode::Mul:
          case Opcode::Div:
          case Opcode::Mod:
          case Opcode::And:
          case Opcode::Or:
          case Opcode::Xor:
          case Opcode::Shl:
          case Opcode::LShr:
          case Opcode::AShr: {
            auto* bin = static_cast<const BinaryInst*>(inst);
            os << "  " << bin->GetName() << " = "
               << OpcodeToString(bin->GetOpcode()) << " "
               << TypeToString(*bin->GetLhs()->GetType()) << " "
               << ValueToString(bin->GetLhs()) << ", "
               << ValueToString(bin->GetRhs()) << "\n";
            break;
          }
          case Opcode::ICmp:
          case Opcode::FCmp: {
            auto* cmp = static_cast<const CmpInst*>(inst);
            os << "  " << cmp->GetName() << " = "
               << OpcodeToString(cmp->GetOpcode()) << " eq "
               << TypeToString(*cmp->GetLhs()->GetType()) << " "
               << ValueToString(cmp->GetLhs()) << ", "
               << ValueToString(cmp->GetRhs()) << "\n";
            break;
          }
          case Opcode::Alloca: {
            auto* alloca = static_cast<const AllocaInst*>(inst);
            os << "  " << alloca->GetName() << " = alloca "
               << TypeToString(*static_cast<const PointerType*>(alloca->GetType().get())->GetPointeeType()) << "\n";
            break;
          }
          case Opcode::Load: {
            auto* load = static_cast<const LoadInst*>(inst);
            os << "  " << load->GetName() << " = load "
               << TypeToString(*load->GetType()) << ", "
               << TypeToString(*load->GetPtr()->GetType()) << " "
               << ValueToString(load->GetPtr()) << "\n";
            break;
          }
          case Opcode::Store: {
            auto* store = static_cast<const StoreInst*>(inst);
            os << "  store " << TypeToString(*store->GetValue()->GetType()) << " "
               << ValueToString(store->GetValue()) << ", "
               << TypeToString(*store->GetPtr()->GetType()) << " "
               << ValueToString(store->GetPtr()) << "\n";
            break;
          }
          case Opcode::Ret: {
            auto* ret = static_cast<const ReturnInst*>(inst);
            os << "  ret " << TypeToString(*ret->GetValue()->GetType()) << " "
               << ValueToString(ret->GetValue()) << "\n";
            break;
          }
          case Opcode::Br: {
            auto* br = static_cast<const BranchInst*>(inst);
            os << "  br label %" << br->GetTarget()->GetName() << "\n";
            break;
          }
          case Opcode::CondBr: {
            auto* condbr = static_cast<const CondBranchInst*>(inst);
            os << "  br i1 " << ValueToString(condbr->GetCond())
               << ", label %" << condbr->GetTrueBlock()->GetName()
               << ", label %" << condbr->GetFalseBlock()->GetName() << "\n";
            break;
          }
          case Opcode::Call: {
            auto* call = static_cast<const CallInst*>(inst);
            os << "  ";
            if (!call->GetName().empty()) {
              os << call->GetName() << " = ";
            }
            os << "call " << TypeToString(*call->GetCallee()->GetType()) << " @"
               << call->GetCallee()->GetName() << "(";
            for (size_t i = 0; i < call->GetArgs().size(); ++i) {
              if (i > 0) os << ", ";
              os << TypeToString(*call->GetArgs()[i]->GetType()) << " "
                 << ValueToString(call->GetArgs()[i]);
            }
            os << ")\n";
            break;
          }
          case Opcode::GEP: {
            auto* gep = static_cast<const GetElementPtrInst*>(inst);
            os << "  " << gep->GetName() << " = getelementptr "
               << TypeToString(*gep->GetPtr()->GetType()) << " "
               << ValueToString(gep->GetPtr());
            for (auto* idx : gep->GetIndices()) {
              os << ", " << TypeToString(*idx->GetType()) << " " << ValueToString(idx);
            }
            os << "\n";
            break;
          }
          case Opcode::Phi: {
            auto* phi = static_cast<const PhiInst*>(inst);
            os << "  " << phi->GetName() << " = phi "
               << TypeToString(*phi->GetType());
            for (const auto& incoming : phi->GetIncomings()) {
              os << " [ " << ValueToString(incoming.first) << ", %"
                 << incoming.second->GetName() << " ]";
            }
            os << "\n";
            break;
          }
        }
      }
    }
    os << "}\n";
  }
}

}  // namespace ir
