import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.text.SimpleDateFormat;
import com.healthmarketscience.jackcess.*;
public class ExportAccess {
  static String[][] TABLES = {      {"ITENS","CODIGO","NUMERO","NOME","GRUPO","UNIDADE","ESTOQUE_MIN","ESTOQUE_IDEAL","ESTOQUE_DISP","CUSTO","VENDA","LOCAL","GAVETA","FABRICANTE","SUBGRUPO","ULTIMA_VENDA","ULTIMA_COMPRA","ARQUIVADO"},
      {"CLIENTES","CODIGO","NOME","GRUPO","CONTATO","CIDADE","UF","TELEFONE","CELULAR","EMAIL","EMAIL_NFE","SITUACAO","BLOQUEADO","ULTIMA_VENDA","CADASTRADO"},
      {"VENDAS","CODIGO","OPERADOR","TOTAL","DIA","CLIENTE","DESCONTO","TOTAL_GERAL","TOTAL_SERVICOS","TOTAL_PECAS","TOTAL_IMPOSTOS","TOTAL_FRETE","SITUACAO_V","CANCELADA"},
      {"ITENS_VENDA","CODIGO","ITEM_CODIGO","DESCRICAO","SERVICO","QTD","VRL_UN","VLR_TOTAL","VENDA","DIA","CUSTO"},
      {"ITENS_ENTRADA","CODIGO","COD_ITEM","NOVOS","DATA_INC"},
      {"ITENS_SAIDA","CODIGO","COD_ITEM","QTD_SAI","DATA_SAIDA"},
      {"OS_PECAS","CODIGO","COD_PECA","QTD","DIA","COD_OS"},
      {"ORDEMS","CODIGO","COD_CLIENTE","ENTRADA","SAIDA","SITUACAO"}};
  static void quoted(Writer w,String value) throws IOException {
    w.write('"');for(int i=0;i<value.length();i++){char c=value.charAt(i);switch(c){case '"':w.write("\\\"");break;case '\\':w.write("\\\\");break;case '\n':w.write("\\n");break;case '\r':w.write("\\r");break;case '\t':w.write("\\t");break;default:if(c<32)w.write(String.format("\\u%04x",(int)c));else w.write(c);}}w.write('"');
  }
  public static void main(String[] args) throws Exception {
    if(args.length!=2){System.err.println("Uso: ExportAccess caminho/Dados.MDB exportacao.json");System.exit(1);}
    File input=new File(args[0]).getCanonicalFile(),output=new File(args[1]).getCanonicalFile();
    if(input.equals(output)||!input.isFile()||output.exists())throw new IOException("Origem inválida ou destino já existente. Use um novo nome de exportação.");
    File temporary=new File(output.getPath()+".tmp");
    try(Database db=new DatabaseBuilder(input).setReadOnly(true).open();Writer w=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(temporary),StandardCharsets.UTF_8))){
      w.write('{');boolean firstTable=true;
      for(String[] cols:TABLES){if(!firstTable)w.write(',');firstTable=false;quoted(w,cols[0]);w.write(":[");boolean firstRow=true;
        for(Row row:db.getTable(cols[0])){if(!firstRow)w.write(',');firstRow=false;w.write('{');for(int c=1;c<cols.length;c++){if(c>1)w.write(',');quoted(w,cols[c]);w.write(':');Object v=row.get(cols[c]);if(v==null)w.write("null");else if(v instanceof Number||v instanceof Boolean)w.write(v.toString());else if(v instanceof java.util.Date)quoted(w,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(v));else quoted(w,v.toString().replace(v instanceof LocalDateTime?'T':'\u0000',v instanceof LocalDateTime?' ':'\u0000'));}w.write('}');}
        w.write(']');System.out.println(cols[0]+": "+db.getTable(cols[0]).getRowCount()+" registros");
      }w.write('}');
    }catch(Exception e){temporary.delete();throw e;}
    java.nio.file.Files.move(temporary.toPath(),output.toPath());System.out.println("Exportação concluída. Envie o JSON pela opção Atualizar base.");
  }
}
