import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
import "../../../chunks/chunk-TG2EQLX2.js";

// builtin/extensions/document-attachments/index.ts
import * as fs from "node:fs";
import * as path from "node:path";
import { spawnSync } from "node:child_process";
var MAX_TEXT_CHARS = 24e3;
var PYTHON_CANDIDATES = [
  process.env.PYTHON,
  "/opt/anaconda3/bin/python3",
  "python3"
].filter((value) => Boolean(value));
function isTextCapable(model) {
  return (model.input ?? []).includes("text");
}
function isSupportedDocument(attachment) {
  return attachment.mimeType === "application/pdf" || attachment.mimeType === "text/html" || attachment.mimeType === "text/plain" || attachment.mimeType === "text/markdown" || attachment.mimeType === "application/json" || attachment.name.endsWith(".html") || attachment.name.endsWith(".htm") || attachment.name.endsWith(".md") || attachment.name.endsWith(".txt") || attachment.name.endsWith(".json") || attachment.name.endsWith(".pdf");
}
function truncateText(text) {
  const normalized = text.replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
  if (normalized.length <= MAX_TEXT_CHARS) return normalized;
  return `${normalized.slice(0, MAX_TEXT_CHARS)}

[Truncated after ${MAX_TEXT_CHARS} characters]`;
}
function runPythonScript(script, fallbackMessage) {
  const failures = [];
  for (const pythonBin of PYTHON_CANDIDATES) {
    const result = spawnSync(pythonBin, ["-c", script], { encoding: "utf8" });
    if (result.status === 0) {
      return result.stdout;
    }
    const detail = (result.stderr || result.stdout || `exit ${result.status}`).trim();
    failures.push(`${pythonBin}: ${detail}`);
  }
  throw new Error(`${fallbackMessage}
${failures.join("\n")}`);
}
function extractHtmlText(filePath) {
  const script = `
from pathlib import Path
from html.parser import HTMLParser

class Extractor(HTMLParser):
    def __init__(self):
        super().__init__()
        self.parts = []
        self.skip_depth = 0
    def handle_starttag(self, tag, attrs):
        if tag in ("script", "style"):
            self.skip_depth += 1
    def handle_endtag(self, tag):
        if tag in ("script", "style") and self.skip_depth > 0:
            self.skip_depth -= 1
    def handle_data(self, data):
        if self.skip_depth:
            return
        data = data.strip()
        if data:
            self.parts.append(data)

p = Path(${JSON.stringify(filePath)})
parser = Extractor()
parser.feed(p.read_text("utf-8"))
print("\\n".join(parser.parts))
`;
  return runPythonScript(script, "Failed to extract HTML text");
}
function extractPdfText(filePath) {
  const script = `
reader = None
errors = []

for module_name in ("pypdf", "PyPDF2"):
    try:
        module = __import__(module_name, fromlist=["PdfReader"])
        reader = module.PdfReader(${JSON.stringify(filePath)})
        break
    except Exception as exc:
        errors.append(f"{module_name}: {exc}")

if reader is None:
    raise RuntimeError(" | ".join(errors) or "No supported PDF reader module found")

parts = []
for page in reader.pages:
    try:
        text = page.extract_text() or ""
    except Exception:
        text = ""
    if text.strip():
        parts.append(text)
print("\\n\\n".join(parts))
`;
  return runPythonScript(script, "Failed to extract PDF text");
}
function extractPlainText(filePath) {
  return fs.readFileSync(filePath, "utf8");
}
function extractDocumentText(attachment) {
  const filePath = attachment.path;
  if (!filePath || !fs.existsSync(filePath)) {
    throw new Error(`Local attachment path is unavailable for ${attachment.name}`);
  }
  const ext = path.extname(filePath).toLowerCase();
  if (attachment.mimeType === "application/pdf" || ext === ".pdf") {
    return extractPdfText(filePath);
  }
  if (attachment.mimeType === "text/html" || ext === ".html" || ext === ".htm") {
    return extractHtmlText(filePath);
  }
  return extractPlainText(filePath);
}
function documentAttachmentsExtension(ctx) {
  ctx.log("Document attachment extension loaded");
  ctx.registerAttachmentHandler({
    name: "local-document-preprocess",
    priority: 20,
    matches(model, attachment) {
      return isTextCapable(model) && isSupportedDocument(attachment) && Boolean(attachment.path);
    },
    async prepare(_model, attachment, prepareCtx) {
      const extracted = extractDocumentText(attachment);
      const text = truncateText(extracted);
      prepareCtx.log(`Document handler extracted ${text.length} chars from ${attachment.name}`);
      const prefix = [
        `[Document: ${attachment.name}]`,
        `MIME: ${attachment.mimeType}`,
        ""
      ].join("\n");
      return {
        items: [
          {
            type: "text",
            text: `${prefix}${text}`
          }
        ]
      };
    }
  });
}
export {
  documentAttachmentsExtension as default
};
