import os
import uuid
import json
import subprocess


def _parse_url_entry(url_entry):
    if isinstance(url_entry, str):
        try:
            parsed = json.loads(url_entry)
            if isinstance(parsed, dict):
                return parsed.get("path", "")
        except (json.JSONDecodeError, TypeError):
            return url_entry
    elif isinstance(url_entry, dict):
        return url_entry.get("path", "")
    return ""


def convert(urls, target_format, options=None, config=None):
    if config is None:
        config = {}

    upload_dir = config.get("UPLOAD_DIR", "static/uploads")
    results = []
    errors = []

    for url_entry in urls:
        file_path = _parse_url_entry(url_entry)
        if not file_path or file_path == "empty":
            continue

        try:
            full_path = os.path.join(upload_dir, file_path)
            if not os.path.exists(full_path):
                full_path = file_path
            if not os.path.exists(full_path):
                errors.append(f"File not found: {os.path.basename(file_path)}")
                continue

            ext = os.path.splitext(full_path)[1].lower().lstrip(".")
            if ext != "pdf":
                errors.append(f"Document compressor only supports PDF files, got: {ext}")
                continue

            out_dir = os.path.join(upload_dir, uuid.uuid4().hex)
            os.makedirs(out_dir, exist_ok=True)

            basename = os.path.splitext(os.path.basename(full_path))[0]
            output_path = os.path.join(out_dir, f"{basename}.pdf")

            cmd = [
                "gs",
                "-sDEVICE=pdfwrite",
                "-dCompatibilityLevel=1.4",
                "-dPDFSETTINGS=/ebook",
                "-dNOPAUSE",
                "-dBATCH",
                "-dQUIET",
                f"-sOutputFile={output_path}",
                full_path,
            ]

            result = subprocess.run(cmd, capture_output=True, timeout=300)

            if result.returncode != 0:
                errors.append(f"Ghostscript error for {os.path.basename(file_path)}: {result.stderr.decode('utf-8', errors='replace')[-500:]}")
                continue

            if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
                results.append(output_path)
            else:
                errors.append(f"Compression failed - no output for {os.path.basename(file_path)}")

        except subprocess.TimeoutExpired:
            errors.append(f"Compression timed out for {os.path.basename(file_path)}")
        except FileNotFoundError:
            errors.append("Ghostscript (gs) not found on system")
        except Exception as e:
            fname = os.path.basename(file_path) if file_path else "unknown"
            errors.append(f"Failed to compress {fname}: {str(e)}")

    if not results and errors:
        return {"error": True, "message": "; ".join(errors)}

    if not results and not errors:
        return {"error": True, "message": "No files were provided for compression."}

    return {
        "error": False,
        "results": results,
        "output_path": results[0] if results else "",
        "errors": errors if errors else None
    }
