/*
 * Programa optimizado Asc2pov
 * Convierte archivos .ASC a .POV y .TIB en una sola pasada
 * Autor: Mario Humberto Tiburcio Zuñiga
 * Revisado y optimizado por ChatGPT (GPT-5)
 */

import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class ASC2POV {

    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Uso: java Asc2pov <nombre_modelo> <carpeta>");
            return;
        }

        String nombre = args[0];
        String prefijo = args[1] + "/";
        String archivoBase = prefijo + nombre + "/" + nombre;
        Path pathAsc = Path.of(archivoBase + ".ASC");

        try {
            List<String> lineas = Files.readAllLines(pathAsc);
            List<String> vertices = new ArrayList<>();

            // Variables para conteo
            int totalVertices = 0;
            int totalCaras = 0;

            // Extraer totales desde la línea 3
            String[] lineaInfo = lineas.get(3).split(" ");
            totalVertices = Integer.parseInt(lineaInfo[2]);
            totalCaras = Integer.parseInt(lineaInfo[4]);

            // Archivos de salida
            FileWriter wPov = new FileWriter(archivoBase + ".pov");
            FileWriter wTib = new FileWriter(archivoBase + ".tib");

            // Encabezado POV-Ray
            wPov.write("#include \"colors.inc\"\n");
            wPov.write("camera {\n");
            wPov.write("  location <1,1,-1>\n");
            wPov.write("  look_at <0,0,0>\n");
            wPov.write("}\n");
            wPov.write("light_source {<4,5,-6> color White}\n");
            wPov.write("plane { y,-1 pigment {checker Black White}}\n");
            wPov.write("#declare " + nombre + " = union {\n");

            // Variables temporales
            String cara = "";
            String rojo = "200", verde = "200", azul = "200";

            int lineaActual = 1;

            // Recorrido único del archivo
            for (String x : lineas) {
                // Leer vértices
                if (x.contains("Vertex") && x.contains("X")) {
                    String[] v = x.split(":");
                    String X = (v[2].split(" "))[0];
                    String Y = (v[3].split(" "))[0];
                    String Z = v[4];
                    vertices.add(X + "," + Y + "," + Z);
                }

                // Leer caras
                if (x.contains("Face") && x.contains("A:") && x.contains("B:") && x.contains("C:")) {
                    String[] f = x.split(":");
                    String a = f[2].split(" ")[0];
                    String b = f[3].split(" ")[0];
                    String c = f[4].split(" ")[0];
                    cara = a + " " + b + " " + c;
                }

                // Leer material y escribir triángulo
                if (x.contains("Material:")) {
                    try {
                        String[] colores = x.split("\"");
                        String rgb = colores[1];
                        rojo = (rgb.split("g"))[0].split("r")[1];
                        verde = (rgb.split("b"))[0].split("g")[1];
                        azul = (rgb.split("a"))[0].split("b")[1];
                    } catch (Exception e) {
                        // Si no hay color válido, usar gris claro
                        rojo = verde = azul = "200";
                    }

                    String[] partes = cara.split(" ");
                    int va = Integer.parseInt(partes[0]);
                    int vb = Integer.parseInt(partes[1]);
                    int vc = Integer.parseInt(partes[2]);

                    // Escribir triángulo en archivo POV
                    wPov.write("triangle {\n");
                    wPov.write("  <" + vertices.get(va) + ">,\n");
                    wPov.write("  <" + vertices.get(vb) + ">,\n");
                    wPov.write("  <" + vertices.get(vc) + ">\n");
                    wPov.write("  pigment { color <" + rojo + "," + verde + "," + azul + ">/255 }\n");
                    wPov.write("}\n");

                    // Escribir coordenadas en archivo TIB
                    wTib.write(vertices.get(va) + "\n");
                    wTib.write(vertices.get(vb) + "\n");
                    wTib.write(vertices.get(vc) + "\n");
                }

                lineaActual++;
            }

            // Cierre de bloque POV
            wPov.write("}\n" + nombre + "\n");
            wPov.close();
            wTib.close();

            System.out.println("Archivo generado: " + archivoBase + ".pov [OK]");
            System.out.println("Archivo generado: " + archivoBase + ".tib [OK]");
            System.out.println("Total de vértices: " + totalVertices);
            System.out.println("Total de caras: " + totalCaras);
            System.out.println("Listo !!!");

        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
