import os
import sys
import json
import shutil
import xml.etree.ElementTree as ET

def process_file(file_path, output_dir):
    os.makedirs(output_dir, exist_ok=True)
    if not os.path.exists(file_path):
        return {"success": False, "error": f"Archivo no encontrado: {file_path}", "found": False}

    ext = os.path.splitext(file_path)[1].lower()

    # 1. Si el archivo es directamente una imagen
    if ext in ['.png', '.jpg', '.jpeg', '.webp', '.bmp']:
        target_path = os.path.join(output_dir, "producto_documento" + ext)
        try:
            shutil.copyfile(file_path, target_path)
            return {"success": True, "found": True, "image_path": target_path}
        except Exception as e:
            return {"success": False, "error": str(e), "found": False}

    # 2. Si es un DOCX
    if ext == '.docx':
        try:
            import zipfile
            import io
            from PIL import Image

            best_img_path = None
            img_w = 0
            img_h = 0
            text_file_path = None

            with zipfile.ZipFile(file_path, 'r') as z:
                # Extraer texto completo
                try:
                    xml_content = z.read('word/document.xml')
                    root = ET.fromstring(xml_content)
                    paragraphs = []
                    for p in root.iter('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}p'):
                        p_text = ''.join(t.text for t in p.iter('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t') if t.text)
                        if p_text.strip():
                            paragraphs.append(p_text.strip())
                    full_text = '\n'.join(paragraphs)
                    text_file_path = os.path.join(output_dir, "documento_texto.txt")
                    with open(text_file_path, "w", encoding="utf-8") as tf:
                        tf.write(full_text)
                except Exception:
                    pass

                # Extraer imágenes incrustadas de word/media/
                candidate_images = []
                for name in z.namelist():
                    if name.startswith('word/media/'):
                        data = z.read(name)
                        img_ext = os.path.splitext(name)[1].lower().lstrip('.')
                        try:
                            img = Image.open(io.BytesIO(data))
                            w, h = img.size
                            if w >= 120 and h >= 120:
                                ratio = float(w) / float(h)
                                score = w * h
                                if 0.5 <= ratio <= 2.2:
                                    score *= 1.5
                                candidate_images.append({
                                    "bytes": data,
                                    "ext": img_ext,
                                    "width": w,
                                    "height": h,
                                    "score": score
                                })
                        except Exception:
                            candidate_images.append({
                                "bytes": data,
                                "ext": img_ext,
                                "width": 0,
                                "height": 0,
                                "score": len(data)
                            })

                if candidate_images:
                    candidate_images.sort(key=lambda x: x["score"], reverse=True)
                    best = candidate_images[0]
                    out_path = os.path.join(output_dir, f"producto_extraido.{best['ext']}")
                    with open(out_path, "wb") as f:
                        f.write(best["bytes"])
                    best_img_path = out_path
                    img_w = best["width"]
                    img_h = best["height"]

            return {
                "success": True,
                "found": best_img_path is not None,
                "image_path": best_img_path or "",
                "text_path": text_file_path or "",
                "width": img_w,
                "height": img_h
            }
        except Exception as e:
            return {"success": False, "error": str(e), "found": False}

    # 3. Si es un PDF
    if ext == '.pdf':
        try:
            import pymupdf as fitz
            doc = fitz.open(file_path)
            candidate_images = []

            for page_idx, page in enumerate(doc):
                for img_info in page.get_images(full=True):
                    xref = img_info[0]
                    try:
                        base_image = doc.extract_image(xref)
                        w = base_image["width"]
                        h = base_image["height"]
                        img_bytes = base_image["image"]
                        img_ext = base_image["ext"]

                        if w >= 120 and h >= 120:
                            ratio = float(w) / float(h)
                            score = (w * h)
                            if 0.5 <= ratio <= 2.0:
                                score *= 1.5

                            candidate_images.append({
                                "bytes": img_bytes,
                                "ext": img_ext,
                                "width": w,
                                "height": h,
                                "score": score,
                                "page": page_idx + 1
                            })
                    except Exception:
                        pass

            # Extraer texto del PDF si existe
            text_file_path = None
            try:
                full_pdf_text = []
                for page in doc:
                    t = page.get_text()
                    if t and t.strip():
                        full_pdf_text.append(t.strip())
                if full_pdf_text:
                    text_file_path = os.path.join(output_dir, "documento_texto.txt")
                    with open(text_file_path, "w", encoding="utf-8") as tf:
                        tf.write("\n\n".join(full_pdf_text))
            except Exception:
                pass

            if candidate_images:
                candidate_images.sort(key=lambda x: x["score"], reverse=True)
                best = candidate_images[0]
                out_path = os.path.join(output_dir, f"producto_extraido.{best['ext']}")
                with open(out_path, "wb") as f:
                    f.write(best["bytes"])
                return {
                    "success": True,
                    "found": True,
                    "image_path": out_path,
                    "text_path": text_file_path or "",
                    "width": best["width"],
                    "height": best["height"],
                    "page": best["page"]
                }
            else:
                if len(doc) > 0:
                    page = doc[0]
                    pix = page.get_pixmap(dpi=150)
                    out_path = os.path.join(output_dir, "pagina_1.png")
                    pix.save(out_path)
                    return {
                        "success": True,
                        "found": True,
                        "image_path": out_path,
                        "text_path": text_file_path or "",
                        "width": pix.width,
                        "height": pix.height,
                        "is_page_render": True
                    }
                return {"success": True, "found": False, "text_path": text_file_path or "", "message": "No se encontraron imágenes en el PDF"}
        except Exception as e:
            return {"success": False, "error": str(e), "found": False}

    return {"success": False, "error": f"Formato no compatible: {ext}", "found": False}

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print(json.dumps({"success": False, "error": "Uso: extract_ficha_image.py <archivo> <carpeta_salida>", "found": False}))
        sys.exit(1)

    file_p = sys.argv[1]
    out_d = sys.argv[2]
    res = process_file(file_p, out_d)
    print(json.dumps(res, ensure_ascii=False))
