unit uProvAlbaranIaImporter;

interface

uses
  System.SysUtils, System.Classes, System.IOUtils, System.JSON, System.Variants,
  System.DateUtils, System.RegularExpressions, System.Net.HttpClient,
  System.Net.HttpClientComponent,
  System.Net.URLClient, System.NetEncoding, System.Generics.Collections, Data.DB,
  FireDAC.Comp.Client, FireDAC.Stan.Param;

type
  TProvAlbaranIaImporter = class
  private
    class function FileToBase64(const AFilePath: string): string;
    class function ISO8601ToDate(const AValue: string): TDateTime;
    class function SanitizeForFileName(const AValue: string): string;
    class function SanitizeNIF(const AValue: string): string;
    class function CleanName(const AName: string): string;
    class function LoadFileAsBlob(const AFilePath: string): TBytes;
    class function GetEmpresasPromptList(AConn: TFDConnection): string;
    class function DetectarEmpresaDestino(AQuery: TFDQuery; AData: TJSONObject): Integer;
    class function FindOrCreateProveedor(AQuery: TFDQuery; AData: TJSONObject): string;
    class procedure CheckAndInsertProveedorMateriaPrima(AQuery: TFDQuery; AIdProveedor: Integer;
      const ACodigo, ADescripcion: string; APrecio, ACantidadPorBulto: Double);
    class procedure LinkDocument(AConn: TFDConnection; const ATableName: string; const AIdRef: Integer;
      const AFilePath, ANewName: string; const AIdEmpresa: Integer);
    class function GetJSONString(AObj: TJSONObject; const AKey: string; const ADefault: string = ''): string;
    class function GetJSONFloat(AObj: TJSONObject; const AKey: string; const ADefault: Double = 0): Double;
    class function GetJSONInt(AObj: TJSONObject; const AKey: string; const ADefault: Integer = 0): Integer;
    class function GetGeminiConfig(out AApiKey, AModel: string): Boolean;
    class function CallGeminiVision(const AFilePath, APrompt, AApiKey, AModel: string): string;
  public
    /// <summary>
    /// Procesa e importa un albarán escaneado (PDF, JPG, PNG) con IA.
    /// Crea el albarán en ge_prov_albaranes y ge_prov_albaranes_detalle,
    /// vincula el archivo físico en ge_documentos y devuelve el ID generado.
    /// </summary>
    class function ImportarAlbaranDesdeArchivo(const AFilePath: string;
      out AIdAlbaranGenerado: Integer; out AErrorMsg: string): Boolean;

    /// <summary>
    /// Procesa e importa una factura escaneada (PDF, JPG, PNG) con IA.
    /// Crea la factura en ge_prov_facturas y ge_prov_facturas_detalle,
    /// vincula el archivo físico en ge_documentos y devuelve el ID generado.
    /// </summary>
    class function ImportarFacturaDesdeArchivo(const AFilePath: string;
      out AIdFacturaGenerada: Integer; out AErrorMsg: string): Boolean;
  end;

implementation

uses
  dmg_Main;

{ TProvAlbaranIaImporter }

class function TProvAlbaranIaImporter.FileToBase64(const AFilePath: string): string;
var
  Stream: TMemoryStream;
  Input: TBytes;
begin
  Stream := TMemoryStream.Create;
  try
    Stream.LoadFromFile(AFilePath);
    SetLength(Input, Stream.Size);
    Stream.Position := 0;
    if Stream.Size > 0 then
      Stream.ReadBuffer(Input[0], Stream.Size);
    Result := TNetEncoding.Base64.EncodeBytesToString(Input);
    Result := Result.Replace(#13, '').Replace(#10, '');
  finally
    Stream.Free;
  end;
end;

class function TProvAlbaranIaImporter.LoadFileAsBlob(const AFilePath: string): TBytes;
var
  Stream: TFileStream;
begin
  Stream := TFileStream.Create(AFilePath, fmOpenRead or fmShareDenyWrite);
  try
    SetLength(Result, Stream.Size);
    if Stream.Size > 0 then
      Stream.ReadBuffer(Result[0], Stream.Size);
  finally
    Stream.Free;
  end;
end;

class function TProvAlbaranIaImporter.ISO8601ToDate(const AValue: string): TDateTime;
begin
  Result := Date;
  if AValue = '' then Exit;
  try
    if not TryISO8601ToDate(AValue, Result) then
    begin
      if not TryStrToDate(AValue, Result) then
        Result := Date;
    end;
  except
    Result := Date;
  end;
end;

class function TProvAlbaranIaImporter.SanitizeForFileName(const AValue: string): string;
const
  InvalidChars: array[0..9] of Char = ('\', '/', ':', '*', '?', '"', '<', '>', '|', ' ');
var
  i: Integer;
begin
  Result := AValue;
  for i := Low(InvalidChars) to High(InvalidChars) do
    Result := Result.Replace(InvalidChars[i], '-');
  Result := Result.Replace('.', '');
  while Pos('--', Result) > 0 do
    Result := Result.Replace('--', '-');
  Result := Result.Trim(['-']);
end;

class function TProvAlbaranIaImporter.SanitizeNIF(const AValue: string): string;
var
  I: Integer;
begin
  Result := '';
  for I := 1 to Length(AValue) do
  begin
    if CharInSet(AValue[I], ['A'..'Z', 'a'..'z', '0'..'9']) then
      Result := Result + AValue[I];
  end;
  Result := Result.ToUpper;

  if (Length(Result) = 10) and (Result[1] = '0') and CharInSet(Result[2], ['X', 'Y', 'Z']) then
    Result := Copy(Result, 2, Length(Result) - 1)
  else if (Length(Result) = 10) and (Result[1] = '0') and CharInSet(Result[10], ['A'..'Z']) and
          (CharInSet(Result[2], ['0'..'9'])) and (CharInSet(Result[9], ['0'..'9'])) then
    Result := Copy(Result, 2, Length(Result) - 1);
end;

class function TProvAlbaranIaImporter.CleanName(const AName: string): string;
var
  I: Integer;
  S: string;
begin
  S := UpperCase(AName);
  S := S.Replace(' S.L.', '').Replace(' SL', '')
        .Replace(' S.A.', '').Replace(' SA', '')
        .Replace(' S.L.U.', '').Replace(' SLU', '')
        .Replace(' S.A.U.', '').Replace(' SAU', '')
        .Replace(' COOP.', '').Replace(' COOP', '')
        .Replace('S.L.', '').Replace('S.A.', '')
        .Replace('C.B.', '').Replace(' CB', '');
  Result := '';
  for I := 1 to Length(S) do
    if CharInSet(S[I], ['A'..'Z', '0'..'9']) then
      Result := Result + S[I];
end;

class function TProvAlbaranIaImporter.GetJSONString(AObj: TJSONObject; const AKey, ADefault: string): string;
var
  V: TJSONValue;
begin
  Result := ADefault;
  if AObj = nil then Exit;
  V := AObj.FindValue(AKey);
  if V <> nil then
    Result := V.Value;
end;

class function TProvAlbaranIaImporter.GetJSONFloat(AObj: TJSONObject; const AKey: string; const ADefault: Double): Double;
var
  V: TJSONValue;
begin
  Result := ADefault;
  if AObj = nil then Exit;
  V := AObj.FindValue(AKey);
  if (V <> nil) and (V is TJSONNumber) then
    Result := TJSONNumber(V).AsDouble
  else if V <> nil then
    TryStrToFloat(V.Value.Replace('.', FormatSettings.DecimalSeparator).Replace(',', FormatSettings.DecimalSeparator), Result);
end;

class function TProvAlbaranIaImporter.GetJSONInt(AObj: TJSONObject; const AKey: string; const ADefault: Integer): Integer;
var
  V: TJSONValue;
begin
  Result := ADefault;
  if AObj = nil then Exit;
  V := AObj.FindValue(AKey);
  if (V <> nil) and (V is TJSONNumber) then
    Result := TJSONNumber(V).AsInt
  else if V <> nil then
    TryStrToInt(V.Value, Result);
end;

class function TProvAlbaranIaImporter.GetEmpresasPromptList(AConn: TFDConnection): string;
var
  Qry: TFDQuery;
  LList: string;
begin
  LList := '';
  try
    Qry := TFDQuery.Create(nil);
    try
      Qry.Connection := AConn;
      Qry.SQL.Text := 'SELECT id, nombre, cif_nif FROM ge_empresas WHERE activo = 1 ORDER BY id';
      Qry.Open;
      while not Qry.Eof do
      begin
        if LList <> '' then LList := LList + ', ';
        LList := LList + Format('%s (%s)', [Qry.FieldByName('cif_nif').AsString.Trim, Qry.FieldByName('nombre').AsString.Trim]);
        Qry.Next;
      end;
    finally
      Qry.Free;
    end;
  except
    LList := 'F23839327 (RAUL ASENCIO COOP.V.), B19856855 (RAUL ASENCIO PASTELERIAS S.L.), B19897628 (PASTELERIA LA TERE S.L.E), F55476741 (AYN CONSULTING COOP. V.), B19897610 (ALHARRUBA S.L.)';
  end;
  Result := LList;
end;

class function TProvAlbaranIaImporter.DetectarEmpresaDestino(AQuery: TFDQuery; AData: TJSONObject): Integer;
var
  LCif, LNom: string;
  LDefEmpresa: Integer;
begin
  LDefEmpresa := StrToIntDef(dmgMain.CurrentCompanyId, 1);
  Result := LDefEmpresa;

  if not Assigned(AData) then Exit;

  LCif := SanitizeNIF(GetJSONString(AData, 'cif_empresa_destino', ''));
  LNom := Trim(GetJSONString(AData, 'nombre_empresa_destino', ''));

  // 1. Búsqueda exacta por CIF/NIF sanitizado en ge_empresas
  if LCif <> '' then
  begin
    AQuery.Close;
    AQuery.SQL.Text := 'SELECT id FROM ge_empresas WHERE UPPER(REPLACE(REPLACE(cif_nif, ''-'', ''''), '' '', '''')) = :cif AND activo = 1 LIMIT 1';
    AQuery.ParamByName('cif').AsString := UpperCase(LCif);
    AQuery.Open;
    if not AQuery.Eof then
    begin
      Result := AQuery.FieldByName('id').AsInteger;
      AQuery.Close;
      Exit;
    end;
    AQuery.Close;
  end;

  // 2. Si no coincide el CIF, búsqueda por similitud de razón social / nombre
  if LNom <> '' then
  begin
    AQuery.Close;
    AQuery.SQL.Text := 'SELECT id FROM ge_empresas WHERE (:nom LIKE CONCAT(''%'', nombre, ''%'') OR nombre LIKE CONCAT(''%'', :nom, ''%'')) AND activo = 1 LIMIT 1';
    AQuery.ParamByName('nom').AsString := LNom;
    AQuery.Open;
    if not AQuery.Eof then
    begin
      Result := AQuery.FieldByName('id').AsInteger;
      AQuery.Close;
      Exit;
    end;
    AQuery.Close;
  end;
end;

class function TProvAlbaranIaImporter.FindOrCreateProveedor(AQuery: TFDQuery; AData: TJSONObject): string;
var
  CleanNif, ANif, ANombre: string;
  ADireccion, ACodigoPostal, APoblacion, AProvincia, ATelefono: string;
  CleanSearchName, CleanSearchDireccion, DbNombre, DbDireccion: string;
begin
  ANif := GetJSONString(AData, 'nif_proveedor');
  ANombre := GetJSONString(AData, 'nombre_proveedor', 'Proveedor Desconocido');
  ADireccion := GetJSONString(AData, 'direccion_proveedor');
  ACodigoPostal := GetJSONString(AData, 'cp_proveedor');
  APoblacion := GetJSONString(AData, 'poblacion_proveedor');
  AProvincia := GetJSONString(AData, 'provincia_proveedor');
  ATelefono := GetJSONString(AData, 'telefono_proveedor');

  CleanNif := SanitizeNIF(ANif);

  // Buscar primero por NIF si está disponible en el documento
  if CleanNif <> '' then
  begin
    AQuery.Close;
    AQuery.SQL.Text := 'SELECT id FROM ge_proveedores WHERE nif = :nif';
    AQuery.ParamByName('nif').DataType := ftString;
    AQuery.ParamByName('nif').AsString := CleanNif;
    AQuery.Open;

    if not AQuery.Eof then
    begin
      Result := AQuery.Fields[0].AsString;
      AQuery.Close;
      Exit;
    end;
    AQuery.Close;
  end;

  // Si no se encuentra por NIF, buscar coincidencia por nombre o por dirección
  CleanSearchName := CleanName(ANombre);
  CleanSearchDireccion := CleanName(ADireccion);
  if (CleanSearchName <> '') or (CleanSearchDireccion <> '') then
  begin
    AQuery.Close;
    AQuery.SQL.Text := 'SELECT id, nif, nombre, direccion FROM ge_proveedores';
    AQuery.Open;
    while not AQuery.Eof do
    begin
      DbNombre := AQuery.FieldByName('nombre').AsString;
      DbDireccion := AQuery.FieldByName('direccion').AsString;
      if ((CleanSearchName <> '') and (CleanName(DbNombre) = CleanSearchName)) or
         ((CleanSearchDireccion <> '') and (CleanName(DbDireccion) = CleanSearchDireccion)) then
      begin
        Result := AQuery.FieldByName('id').AsString;
        AQuery.Close;
        Exit;
      end;
      AQuery.Next;
    end;
    AQuery.Close;
  end;

  if CleanNif = '' then
    raise Exception.Create('NIF de proveedor vacío o inválido, y no se encontró coincidencia por nombre: ' + ANombre);

  // No existe: crear nuevo proveedor
  AQuery.Close;
  AQuery.SQL.Text := 'INSERT INTO ge_proveedores (nif, nombre, direccion, codigo_postal, poblacion, provincia, telefono_1, activo) ' +
                     'VALUES (:nif, :nombre, :dir, :cp, :pob, :prov, :tel, 1)';
  AQuery.ParamByName('nif').DataType := ftString;
  AQuery.ParamByName('nombre').DataType := ftString;
  AQuery.ParamByName('dir').DataType := ftString;
  AQuery.ParamByName('cp').DataType := ftString;
  AQuery.ParamByName('pob').DataType := ftString;
  AQuery.ParamByName('prov').DataType := ftString;
  AQuery.ParamByName('tel').DataType := ftString;

  AQuery.ParamByName('nif').AsString := CleanNif;
  AQuery.ParamByName('nombre').AsString := Copy(ANombre, 1, 50);
  AQuery.ParamByName('dir').AsString := Copy(ADireccion, 1, 50);
  AQuery.ParamByName('cp').AsString := Copy(ACodigoPostal, 1, 5);
  AQuery.ParamByName('pob').AsString := Copy(APoblacion, 1, 50);
  AQuery.ParamByName('prov').AsString := Copy(AProvincia, 1, 50);
  AQuery.ParamByName('tel').AsString := Copy(ATelefono, 1, 50);
  AQuery.ExecSQL;

  AQuery.SQL.Text := 'SELECT LAST_INSERT_ID()';
  AQuery.Open;
  Result := AQuery.Fields[0].AsString;
  AQuery.Close;
end;

class procedure TProvAlbaranIaImporter.CheckAndInsertProveedorMateriaPrima(AQuery: TFDQuery; AIdProveedor: Integer;
  const ACodigo, ADescripcion: string; APrecio, ACantidadPorBulto: Double);
var
  MatId: Variant;
begin
  if (ACodigo = '') or (AIdProveedor <= 0) then Exit;

  AQuery.Close;
  AQuery.SQL.Text := 'SELECT id, descripcion FROM ge_proveedores_materias_primas ' +
                    'WHERE id_proveedor = :idprov AND codigo_articulo_proveedor = :cod LIMIT 1';
  AQuery.ParamByName('idprov').DataType := ftInteger;
  AQuery.ParamByName('idprov').AsInteger := AIdProveedor;
  AQuery.ParamByName('cod').DataType := ftString;
  AQuery.ParamByName('cod').AsString := ACodigo;
  AQuery.Open;
  
  if not AQuery.Eof then
  begin
    AQuery.Close;
    AQuery.SQL.Text := 'UPDATE ge_proveedores_materias_primas ' +
                      'SET ult_precio = :precio ' +
                      'WHERE id_proveedor = :idprov AND codigo_articulo_proveedor = :cod';
    AQuery.ParamByName('precio').DataType := ftFloat;
    AQuery.ParamByName('precio').AsFloat := APrecio;
    AQuery.ParamByName('idprov').DataType := ftInteger;
    AQuery.ParamByName('idprov').AsInteger := AIdProveedor;
    AQuery.ParamByName('cod').DataType := ftString;
    AQuery.ParamByName('cod').AsString := ACodigo;
    AQuery.ExecSQL;
  end
  else
  begin
    AQuery.Close;
    MatId := Null;
    AQuery.SQL.Text := 'SELECT id FROM ge_materias_primas WHERE descripcion = :desc LIMIT 1';
    AQuery.ParamByName('desc').DataType := ftString;
    AQuery.ParamByName('desc').AsString := ADescripcion;
    AQuery.Open;
    if not AQuery.Eof then
      MatId := AQuery.Fields[0].AsInteger;
    AQuery.Close;
    
    AQuery.SQL.Text := 'INSERT INTO ge_proveedores_materias_primas (activo, id_proveedor, codigo_articulo_proveedor, descripcion, id_materia_prima, ult_precio, cantidad_por_bulto) ' +
                      'VALUES (1, :idprov, :cod, :desc, :idmat, :precio, :cantbulto)';
    AQuery.ParamByName('idprov').DataType := ftInteger;
    AQuery.ParamByName('idprov').AsInteger := AIdProveedor;
    AQuery.ParamByName('cod').DataType := ftString;
    AQuery.ParamByName('cod').AsString := ACodigo;
    AQuery.ParamByName('desc').DataType := ftString;
    AQuery.ParamByName('desc').AsString := Copy(ADescripcion, 1, 50);
    AQuery.ParamByName('idmat').DataType := ftInteger;
    AQuery.ParamByName('idmat').Value := MatId;
    AQuery.ParamByName('precio').DataType := ftFloat;
    AQuery.ParamByName('precio').AsFloat := APrecio;
    AQuery.ParamByName('cantbulto').DataType := ftFloat;
    AQuery.ParamByName('cantbulto').AsFloat := ACantidadPorBulto;
    AQuery.ExecSQL;
  end;
end;

class procedure TProvAlbaranIaImporter.LinkDocument(AConn: TFDConnection; const ATableName: string; const AIdRef: Integer;
  const AFilePath, ANewName: string; const AIdEmpresa: Integer);
var
  Query: TFDQuery;
  Ext: string;
  BlobStream: TBytesStream;
begin
  Ext := TPath.GetExtension(AFilePath).ToLower;
  Query := TFDQuery.Create(nil);
  try
    Query.Connection := AConn;
    Query.SQL.Text := 'INSERT INTO ge_documentos (id_empresa, fecha, archivo, nombre_archivo, extension, id_albaran_proveedor, id_factura_proveedor, publicar) ' +
                      'VALUES (:id_empresa, :fecha, :archivo, :nombre_archivo, :extension, :id_albaran_proveedor, :id_factura_proveedor, 1)';
    
    Query.ParamByName('id_empresa').DataType := ftInteger;
    Query.ParamByName('fecha').DataType := ftDate;
    Query.ParamByName('archivo').DataType := ftBlob;
    Query.ParamByName('nombre_archivo').DataType := ftString;
    Query.ParamByName('nombre_archivo').Size := 100;
    Query.ParamByName('extension').DataType := ftString;
    Query.ParamByName('extension').Size := 10;
    Query.ParamByName('id_albaran_proveedor').DataType := ftInteger;
    Query.ParamByName('id_factura_proveedor').DataType := ftInteger;

    if AIdEmpresa > 0 then
      Query.ParamByName('id_empresa').AsInteger := AIdEmpresa
    else
      Query.ParamByName('id_empresa').AsInteger := StrToIntDef(dmgMain.CurrentCompanyId, 1);

    Query.ParamByName('fecha').AsDate := Date;
    Query.ParamByName('nombre_archivo').AsString := Copy(TPath.GetFileName(ANewName).Replace(#0, '').Trim, 1, 100);
    Query.ParamByName('extension').AsString := Copy(Ext.Replace('.', ''), 1, 10);
    
    Query.ParamByName('id_albaran_proveedor').Clear;
    Query.ParamByName('id_factura_proveedor').Clear;
    if SameText(ATableName, 'ge_prov_facturas') then
      Query.ParamByName('id_factura_proveedor').AsInteger := AIdRef
    else
      Query.ParamByName('id_albaran_proveedor').AsInteger := AIdRef;

    BlobStream := TBytesStream.Create(LoadFileAsBlob(AFilePath));
    try
      BlobStream.Position := 0;
      Query.ParamByName('archivo').LoadFromStream(BlobStream, ftBlob);
      Query.ExecSQL;
    finally
      BlobStream.Free;
    end;
  finally
    Query.Free;
  end;
end;

class function TProvAlbaranIaImporter.GetGeminiConfig(out AApiKey, AModel: string): Boolean;
var
  LQuery: TFDQuery;
  LDocIniPath: string;
  LSL: TStringList;
  LContent: string;
  LDec: TBytes;
  I: Integer;
begin
  Result := False;
  AApiKey := '';
  AModel := 'gemini-3.7-flash';

  // 1. Intentar desde ge_empresas de la empresa activa
  if Assigned(dmgMain) and Assigned(dmgMain.dbConn) and dmgMain.dbConn.Connected then
  begin
    LQuery := TFDQuery.Create(nil);
    try
      LQuery.Connection := dmgMain.dbConn;
      LQuery.SQL.Text := 'SELECT IAmodelo, apikey FROM ge_empresas WHERE id = :id';
      LQuery.ParamByName('id').AsString := dmgMain.CurrentCompanyId;
      LQuery.Open;
      if not LQuery.IsEmpty then
      begin
        AApiKey := dmgMain.DecryptStr(LQuery.FieldByName('apikey').AsString);
        AModel := dmgMain.DecryptStr(LQuery.FieldByName('IAmodelo').AsString);
        if (AModel = '') or (AModel = 'gemini-1.5-flash') then
          AModel := 'gemini-3.7-flash';
        if (AApiKey <> '') and (AApiKey <> 'YOUR_GEMINI_API_KEY') then
          Exit(True);
      end;
    finally
      LQuery.Free;
    end;
  end;

  // 2. Intentar desde el archivo de configuración de Gestión Documental (gestiondoc.ini)
  LDocIniPath := 'C:\CLIENTES\ASENCIO\gestiondoc.ini';
  if not FileExists(LDocIniPath) then
    LDocIniPath := 'c:\fuentes\proyectos delphi\GESTION DOCUMENTAL\RAUL_ASENCIO\gestiondoc.ini';

  if FileExists(LDocIniPath) then
  begin
    LSL := TStringList.Create;
    try
      try
        LSL.LoadFromFile(LDocIniPath, TEncoding.UTF8);
        LContent := LSL.Text.Trim;
        if LContent.StartsWith('AGRDOC:') then
        begin
          LContent := LContent.Substring(7);
          LDec := TNetEncoding.Base64.DecodeStringToBytes(LContent);
          for I := 0 to High(LDec) do
            LDec[I] := LDec[I] xor 127;
          LContent := TEncoding.UTF8.GetString(LDec);
        end;

        LSL.Text := LContent;
        AApiKey := LSL.Values['apikey'];
        if AApiKey = '' then
          AApiKey := LSL.Values['ApiKey'];
        
        if LSL.Values['iamodelo'] <> '' then
          AModel := LSL.Values['iamodelo']
        else if LSL.Values['IAModelo'] <> '' then
          AModel := LSL.Values['IAModelo'];

        if (AModel = '') or (AModel = 'gemini-1.5-flash') then
          AModel := 'gemini-3.7-flash';

        if (AApiKey <> '') and (AApiKey <> 'YOUR_GEMINI_API_KEY') then
          Result := True;
      except
        // Continuar
      end;
    finally
      LSL.Free;
    end;
  end;
end;

class function TProvAlbaranIaImporter.CallGeminiVision(const AFilePath, APrompt, AApiKey, AModel: string): string;
var
  HTTP: TNetHTTPClient;
  RequestBody, CandidateObj, SubContentObj, ContentObj, TextPart, Part, InlineData: TJSONObject;
  ResponseJSON: TJSONObject;
  ContentsArr, PartsArr, CandidatesArr, SubPartsArr: TJSONArray;
  Response: IHTTPResponse;
  URL, MimeType, Ext: string;
  SS: TStringStream;
begin
  Result := '';
  Ext := TPath.GetExtension(AFilePath).ToLower;
  if Ext = '.pdf' then MimeType := 'application/pdf'
  else if (Ext = '.jpg') or (Ext = '.jpeg') then MimeType := 'image/jpeg'
  else if Ext = '.png' then MimeType := 'image/png'
  else
    raise Exception.Create('Extensión de archivo no soportada por la IA: ' + Ext);

  HTTP := TNetHTTPClient.Create(nil);
  RequestBody := TJSONObject.Create;
  try
    URL := 'https://generativelanguage.googleapis.com/v1beta/models/' + AModel + ':generateContent?key=' + AApiKey;

    ContentsArr := TJSONArray.Create;
    ContentObj := TJSONObject.Create;
    PartsArr := TJSONArray.Create;

    TextPart := TJSONObject.Create;
    TextPart.AddPair('text', APrompt);
    PartsArr.Add(TextPart);

    Part := TJSONObject.Create;
    InlineData := TJSONObject.Create;
    InlineData.AddPair('mime_type', MimeType);
    InlineData.AddPair('data', FileToBase64(AFilePath));
    Part.AddPair('inline_data', InlineData);
    PartsArr.Add(Part);

    ContentObj.AddPair('parts', PartsArr);
    ContentsArr.Add(ContentObj);
    RequestBody.AddPair('contents', ContentsArr);

    HTTP.ContentType := 'application/json';
    HTTP.ConnectionTimeout := 60000;
    HTTP.ResponseTimeout := 180000;
    SS := TStringStream.Create(RequestBody.ToJSON, TEncoding.UTF8);
    try
      Response := HTTP.Post(URL, SS);
    finally
      SS.Free;
    end;

    if Response.StatusCode = 200 then
    begin
      ResponseJSON := TJSONObject.ParseJSONValue(Response.ContentAsString) as TJSONObject;
      if Assigned(ResponseJSON) then
      try
        CandidatesArr := ResponseJSON.FindValue('candidates') as TJSONArray;
        if Assigned(CandidatesArr) and (CandidatesArr.Count > 0) then
        begin
          CandidateObj := CandidatesArr.Items[0] as TJSONObject;
          SubContentObj := CandidateObj.FindValue('content') as TJSONObject;
          if Assigned(SubContentObj) then
          begin
            SubPartsArr := SubContentObj.FindValue('parts') as TJSONArray;
            if Assigned(SubPartsArr) and (SubPartsArr.Count > 0) then
            begin
              Result := (SubPartsArr.Items[0] as TJSONObject).FindValue('text').Value;
              Result := Result.Replace('```json', '').Replace('```', '').Trim;
            end
            else
              raise Exception.Create('La respuesta no contiene partes legibles ("parts")');
          end
          else
            raise Exception.Create('La respuesta no contiene contenido estructurado ("content")');
        end
        else
          raise Exception.Create('La IA no devolvió candidatos: ' + Response.ContentAsString);
      finally
        ResponseJSON.Free;
      end;
    end
    else
      raise Exception.Create('Error HTTP ' + Response.StatusCode.ToString + ' en API Gemini: ' + Response.ContentAsString);
  finally
    RequestBody.Free;
    HTTP.Free;
  end;
end;

class function TProvAlbaranIaImporter.ImportarAlbaranDesdeArchivo(const AFilePath: string;
  out AIdAlbaranGenerado: Integer; out AErrorMsg: string): Boolean;
var
  ApiKey, Model, FullPrompt, JsonText, DocNumero, IdProv: string;
  NewDocName, CadStr, LoteStr, DescStr: string;
  JSValue: TJSONValue;
  MainObj, DataObj, DetObj: TJSONObject;
  Details: TJSONArray;
  Query: TFDQuery;
  IdEmpresaNum, MasterID, I, LIva: Integer;
  LCant, LPrec, LDesc, LDescAbs, LBase, LTot, LBultos, LCantBulto, RegisteredCantBulto, DocPrice: Double;
begin
  Result := False;
  AIdAlbaranGenerado := 0;
  AErrorMsg := '';

  if not FileExists(AFilePath) then
  begin
    AErrorMsg := 'El archivo seleccionado no existe: ' + AFilePath;
    Exit;
  end;

  if not GetGeminiConfig(ApiKey, Model) then
  begin
    AErrorMsg := 'No se encontró una API Key de Gemini válida configurada en la empresa ni en la configuración de Gestión Documental.';
    Exit;
  end;

  // Construir el prompt especializado exactamente como en uProcessor.pas
  FullPrompt :=
    'Eres un sistema experto en OCR y extracción de datos de documentos comerciales y laborales españoles. ' +
    'Analiza este documento de ALBARÁN de proveedor y extrae con máxima precisión todos sus datos.' + sLineBreak + sLineBreak +
    'INSTRUCCIONES CRÍTICAS SOBRE FECHAS:' + sLineBreak +
    '- Las fechas pueden estar ESCRITAS A MANO, impresas o en formato mixto.' + sLineBreak +
    '- Busca la fecha en toda la superficie del documento: cabecera, sellos, anotaciones manuscritas, fechas de expedición/caducidad.' + sLineBreak +
    '- Devuelve SIEMPRE la fecha en formato YYYY-MM-DD.' + sLineBreak + sLineBreak +
    'INSTRUCCIONES SOBRE CÓDIGOS DE ARTÍCULO:' + sLineBreak +
    '- Cada línea de detalle tiene una columna CÓDIGO o REFERENCIA. NUNCA la omitas.' + sLineBreak +
    '- El código puede ser numérico (ej: "010193"), alfanumérico (ej: "SPR-001") o un código de barras. Si no hay, usa "".' + sLineBreak + sLineBreak +
    'FORMATO DE RESPUESTA: Devuelve ÚNICAMENTE un objeto JSON (sin markdown ni texto adicional) con esta estructura:' + sLineBreak +
    '{"tipo": "ALBARAN", "datos": {' + sLineBreak +
    '  "cif_empresa_destino": "CIF de la empresa compradora registrada: ' + GetEmpresasPromptList(dmgMain.dbConn) + '",' + sLineBreak +
    '  "nombre_empresa_destino": "Razón social de la empresa compradora receptora",' + sLineBreak +
    '  "nif_proveedor": "CIF/NIF del emisor",' + sLineBreak +
    '  "nombre_proveedor": "Razón social completa",' + sLineBreak +
    '  "direccion_proveedor": "Dirección fiscal",' + sLineBreak +
    '  "poblacion_proveedor": "Población",' + sLineBreak +
    '  "cp_proveedor": "Código postal",' + sLineBreak +
    '  "provincia_proveedor": "Provincia",' + sLineBreak +
    '  "telefono_proveedor": "Teléfono",' + sLineBreak +
    '  "numero": "Número de albarán",' + sLineBreak +
    '  "fecha": "YYYY-MM-DD",' + sLineBreak +
    '  "base": 0.0,' + sLineBreak +
    '  "iva": 0.0,' + sLineBreak +
    '  "total": 0.0,' + sLineBreak +
    '  "detalles": [' + sLineBreak +
    '    {' + sLineBreak +
    '      "codigo": "Código o referencia del artículo",' + sLineBreak +
    '      "descripcion": "Descripción del producto o servicio",' + sLineBreak +
    '      "bultos": 1.0,' + sLineBreak +
    '      "cantidad_bulto": 1.0,' + sLineBreak +
    '      "cantidad": 1.0,' + sLineBreak +
    '      "precio": 0.0,' + sLineBreak +
    '      "tipo_iva": 10,' + sLineBreak +
    '      "descuento": 0.0,' + sLineBreak +
    '      "descuento_importe": 0.0,' + sLineBreak +
    '      "total": 0.0,' + sLineBreak +
    '      "lote": "Lote si existe",' + sLineBreak +
    '      "fecha_caducidad": "YYYY-MM-DD si existe"' + sLineBreak +
    '    }' + sLineBreak +
    '  ]' + sLineBreak +
    '}}' + sLineBreak + sLineBreak +
    'REGLAS ADICIONALES:' + sLineBreak +
    '- REGLA DE PACKS/BULTOS: Analiza la descripción o columnas en busca de indicaciones de unidades o peso por bulto/caja (ej: "caja-2,5 kg", "6 BRIK X 1 L.", "50u").' + sLineBreak +
    '- DETERMINACIÓN DEL PRECIO UNITARIO Y CANTIDAD: "bultos" es cajas/packs, "cantidad" es bultos * cantidad_bulto. "precio" es el precio unitario individual.' + sLineBreak +
    '- LOTES MÚLTIPLES: Si un artículo desglosa varios lotes o caducidades, genera un objeto independiente en el array "detalles" para cada lote.' + sLineBreak +
    '- IDENTIFICACIÓN EMPRESA DESTINO: Identifica cuál de nuestras empresas receptoras es la compradora y pon su CIF exacto en "cif_empresa_destino".' + sLineBreak +
    '- No inventes datos. Si un campo no es legible, usa cadena vacía "" o 0.';

  try
    JsonText := CallGeminiVision(AFilePath, FullPrompt, ApiKey, Model);
  except
    on E: Exception do
    begin
      AErrorMsg := 'Error al invocar la API de Gemini: ' + E.Message;
      Exit;
    end;
  end;

  JSValue := TJSONObject.ParseJSONValue(JsonText);
  if not Assigned(JSValue) or not (JSValue is TJSONObject) then
  begin
    AErrorMsg := 'La respuesta de la IA no contiene un JSON estructurado válido: ' + JsonText;
    if Assigned(JSValue) then JSValue.Free;
    Exit;
  end;

  MainObj := JSValue as TJSONObject;
  try
    DataObj := MainObj.FindValue('datos') as TJSONObject;
    if not Assigned(DataObj) then
      DataObj := MainObj;

    dmgMain.dbConn.StartTransaction;
    Query := TFDQuery.Create(nil);
    try
      Query.Connection := dmgMain.dbConn;

      // 0. Detectar Empresa Destino según CIF/Razón Social del receptor
      IdEmpresaNum := DetectarEmpresaDestino(Query, DataObj);

      // 1. Buscar o Crear Proveedor
      IdProv := FindOrCreateProveedor(Query, DataObj);

      DocNumero := GetJSONString(DataObj, 'numero', 'S/N');

      // Comprobar Duplicado usando idproveedor e idempresa
      Query.Close;
      Query.SQL.Text := 'SELECT COUNT(*) FROM ge_prov_albaranes WHERE documento = :num AND idproveedor = :idprov AND idempresa = :idempresa';
      Query.ParamByName('num').DataType := ftString;
      Query.ParamByName('idprov').DataType := ftInteger;
      Query.ParamByName('idempresa').DataType := ftInteger;
      Query.ParamByName('num').AsString := DocNumero;
      Query.ParamByName('idprov').AsInteger := StrToIntDef(IdProv, 0);
      Query.ParamByName('idempresa').AsInteger := IdEmpresaNum;
      Query.Open;
      if Query.Fields[0].AsInteger > 0 then
      begin
        Query.Close;
        raise Exception.Create('Ya existe un albarán registrado con este número (' + DocNumero + ') para este proveedor en la empresa destino.');
      end;
      Query.Close;

      // 2. Insertar Cabecera del Albarán
      Query.SQL.Text := 'INSERT INTO ge_prov_albaranes (idempresa, idproveedor, documento, fecha, base, totaliva, totalentrada) ' +
                        'VALUES (:idempresa, :idproveedor, :documento, :fecha, :base, :totaliva, :totalentrada)';
      Query.ParamByName('idempresa').DataType := ftInteger;
      Query.ParamByName('idproveedor').DataType := ftInteger;
      Query.ParamByName('documento').DataType := ftString;
      Query.ParamByName('fecha').DataType := ftDate;
      Query.ParamByName('base').DataType := ftFloat;
      Query.ParamByName('totaliva').DataType := ftFloat;
      Query.ParamByName('totalentrada').DataType := ftFloat;

      Query.ParamByName('idempresa').AsInteger := IdEmpresaNum;
      Query.ParamByName('idproveedor').AsInteger := StrToIntDef(IdProv, 0);
      Query.ParamByName('documento').AsString := DocNumero;
      Query.ParamByName('fecha').AsDate := ISO8601ToDate(GetJSONString(DataObj, 'fecha', DateToStr(Date)));
      Query.ParamByName('base').AsFloat := GetJSONFloat(DataObj, 'base');
      Query.ParamByName('totaliva').AsFloat := GetJSONFloat(DataObj, 'iva');
      Query.ParamByName('totalentrada').AsFloat := GetJSONFloat(DataObj, 'total');
      Query.ExecSQL;

      // Recuperar ID autoincremental
      Query.SQL.Text := 'SELECT LAST_INSERT_ID()';
      Query.Open;
      MasterID := Query.Fields[0].AsInteger;
      Query.Close;

      // 3. Insertar Detalles
      if (DataObj.FindValue('detalles') <> nil) and (DataObj.FindValue('detalles') is TJSONArray) then
      begin
        Details := DataObj.FindValue('detalles') as TJSONArray;
        for I := 0 to Details.Count - 1 do
        begin
          DetObj := Details.Items[I] as TJSONObject;

          LCant := GetJSONFloat(DetObj, 'cantidad');
          LPrec := GetJSONFloat(DetObj, 'precio');
          LBultos := GetJSONFloat(DetObj, 'bultos', 1.0);
          if LBultos <= 0 then LBultos := 1.0;
          LCantBulto := GetJSONFloat(DetObj, 'cantidad_bulto', 1.0);
          if LCantBulto <= 0 then LCantBulto := 1.0;

          // Si el artículo ya existe en ge_proveedores_materias_primas, usar cantidad_por_bulto registrada
          Query.Close;
          Query.SQL.Text := 'SELECT cantidad_por_bulto FROM ge_proveedores_materias_primas ' +
                            'WHERE id_proveedor = :idprov AND codigo_articulo_proveedor = :cod LIMIT 1';
          Query.ParamByName('idprov').DataType := ftInteger;
          Query.ParamByName('idprov').AsInteger := StrToIntDef(IdProv, 0);
          Query.ParamByName('cod').DataType := ftString;
          Query.ParamByName('cod').AsString := GetJSONString(DetObj, 'codigo', '');
          Query.Open;
          if not Query.Eof and not Query.Fields[0].IsNull then
          begin
            RegisteredCantBulto := Query.Fields[0].AsFloat;
            if RegisteredCantBulto > 0 then
            begin
              DocPrice := LPrec * LCantBulto;
              LCantBulto := RegisteredCantBulto;
              LCant := LBultos * LCantBulto;
              LPrec := DocPrice / LCantBulto;
            end;
          end;
          Query.Close;

          LDesc := GetJSONFloat(DetObj, 'descuento');
          LDescAbs := GetJSONFloat(DetObj, 'descuento_importe');
          LIva  := GetJSONInt(DetObj, 'tipo_iva');

          // Calcular descuentos mutuos
          if (LDescAbs <> 0) and (LDesc = 0) then
          begin
            if LCant > 0 then
              LDescAbs := -Abs(LDescAbs / LCant)
            else
              LDescAbs := -Abs(LDescAbs);

            if LPrec > 0 then
              LDesc := (Abs(LDescAbs) / LPrec) * 100
            else
              LDesc := 0;
          end
          else if (LDesc <> 0) then
          begin
            LDescAbs := -Abs(LPrec * LDesc / 100);
          end
          else
          begin
            LDescAbs := 0;
            LDesc := 0;
          end;

          LBase := LCant * (LPrec + LDescAbs);
          LTot  := LBase * (1 + (LIva / 100));

          Query.SQL.Text := 'INSERT INTO ge_prov_albaranes_detalle (idempresa, idalbaran, idproveedor, codigo, descripcion, ' +
                            'lote, bultos, cantidad_bulto, cantidad, precio, tipo_iva, base, total, fecha_caducidad, descuento_porcentaje, descuento_precio) ' +
                            'VALUES (:idempresa, :idalbaran, :idproveedor, :codigo, :descripcion, :lote, :bultos, :cantidad_bulto, :cantidad, :precio, :tipo_iva, :base, :total, :fecha_caducidad, :descuento_porcentaje, :descuento_precio)';

          Query.ParamByName('idempresa').DataType := ftInteger;
          Query.ParamByName('idalbaran').DataType := ftInteger;
          Query.ParamByName('idproveedor').DataType := ftInteger;
          Query.ParamByName('codigo').DataType := ftString;
          Query.ParamByName('descripcion').DataType := ftString;
          Query.ParamByName('lote').DataType := ftString;
          Query.ParamByName('bultos').DataType := ftFloat;
          Query.ParamByName('cantidad_bulto').DataType := ftFloat;
          Query.ParamByName('cantidad').DataType := ftFloat;
          Query.ParamByName('precio').DataType := ftFloat;
          Query.ParamByName('tipo_iva').DataType := ftInteger;
          Query.ParamByName('base').DataType := ftFloat;
          Query.ParamByName('total').DataType := ftFloat;
          Query.ParamByName('descuento_porcentaje').DataType := ftFloat;
          Query.ParamByName('descuento_precio').DataType := ftFloat;
          Query.ParamByName('fecha_caducidad').DataType := ftDate;

          Query.ParamByName('idempresa').AsInteger := IdEmpresaNum;
          Query.ParamByName('idalbaran').AsInteger := MasterID;
          Query.ParamByName('idproveedor').AsInteger := StrToIntDef(IdProv, 0);
          Query.ParamByName('codigo').AsString := GetJSONString(DetObj, 'codigo', '');
          DescStr := GetJSONString(DetObj, 'descripcion', 'Sin descripción');
          Query.ParamByName('descripcion').AsString := DescStr;

          // Lote
          LoteStr := Trim(GetJSONString(DetObj, 'lote', ''));
          if (LoteStr = '') or (LoteStr = 'null') then
          begin
            if TRegEx.IsMatch(DescStr, 'LOTE[:\s]*([\w\-\.]+)', [roIgnoreCase]) then
              LoteStr := TRegEx.Match(DescStr, 'LOTE[:\s]*([\w\-\.]+)', [roIgnoreCase]).Groups[1].Value;
          end;
          if (LoteStr = '') or (LoteStr = 'null') then
            LoteStr := DocNumero;

          Query.ParamByName('lote').AsString := LoteStr;
          Query.ParamByName('bultos').AsFloat := LBultos;
          Query.ParamByName('cantidad_bulto').AsFloat := LCantBulto;
          Query.ParamByName('cantidad').AsFloat := LCant;
          Query.ParamByName('precio').AsFloat := LPrec;
          Query.ParamByName('tipo_iva').AsInteger := LIva;
          Query.ParamByName('base').AsFloat := LBase;
          Query.ParamByName('total').AsFloat := LTot;
          Query.ParamByName('descuento_porcentaje').AsFloat := LDesc;
          Query.ParamByName('descuento_precio').AsFloat := LDescAbs;

          CadStr := GetJSONString(DetObj, 'fecha_caducidad', '');
          if (CadStr <> '') and (CadStr <> 'null') then
            Query.ParamByName('fecha_caducidad').AsDate := ISO8601ToDate(CadStr)
          else
            Query.ParamByName('fecha_caducidad').Value := Null;

          Query.ExecSQL;
          CheckAndInsertProveedorMateriaPrima(Query, StrToIntDef(IdProv, 0), GetJSONString(DetObj, 'codigo', ''), DescStr, LPrec, LCantBulto);
        end;
      end;

      // 4. Guardar archivo original escaneado en ge_documentos
      NewDocName := SanitizeForFileName(
        GetJSONString(DataObj, 'fecha', DateToStr(Date)) + '_' +
        SanitizeNIF(GetJSONString(DataObj, 'nif_proveedor', 'XX')) + '_' +
        GetJSONString(DataObj, 'nombre_proveedor', 'XX') + '_' +
        'ALB_' +
        DocNumero
      ) + TPath.GetExtension(AFilePath);

      LinkDocument(dmgMain.dbConn, 'ge_prov_albaranes', MasterID, AFilePath, NewDocName, IdEmpresaNum);

      dmgMain.dbConn.Commit;
      AIdAlbaranGenerado := MasterID;
      Result := True;
    finally
      Query.Free;
    end;
  finally
    JSValue.Free;
  end;
end;

class function TProvAlbaranIaImporter.ImportarFacturaDesdeArchivo(const AFilePath: string;
  out AIdFacturaGenerada: Integer; out AErrorMsg: string): Boolean;
var
  ApiKey, Model, FullPrompt, JsonText, DocNumero, IdProv: string;
  NewDocName, CadStr, LoteStr, DescStr: string;
  JSValue: TJSONValue;
  MainObj, DataObj, DetObj: TJSONObject;
  Details: TJSONArray;
  Query: TFDQuery;
  IdEmpresaNum, MasterID, I, LIva: Integer;
  LCant, LPrec, LDesc, LDescAbs, LBase, LTot, LBultos, LCantBulto, RegisteredCantBulto, DocPrice: Double;
begin
  Result := False;
  AIdFacturaGenerada := 0;
  AErrorMsg := '';

  if not FileExists(AFilePath) then
  begin
    AErrorMsg := 'El archivo seleccionado no existe: ' + AFilePath;
    Exit;
  end;

  if not GetGeminiConfig(ApiKey, Model) then
  begin
    AErrorMsg := 'No se encontró una API Key de Gemini válida configurada en la empresa ni en la configuración de Gestión Documental.';
    Exit;
  end;

  FullPrompt :=
    'Eres un sistema experto en OCR y extracción de datos de documentos comerciales y laborales españoles. ' +
    'Analiza este documento de FACTURA de proveedor y extrae con máxima precisión todos sus datos.' + sLineBreak + sLineBreak +
    'INSTRUCCIONES CRÍTICAS SOBRE FECHAS:' + sLineBreak +
    '- Las fechas pueden estar ESCRITAS A MANO, impresas o en formato mixto.' + sLineBreak +
    '- Busca la fecha en toda la superficie del documento: cabecera, sellos, anotaciones manuscritas, fechas de expedición/caducidad.' + sLineBreak +
    '- Devuelve SIEMPRE la fecha en formato YYYY-MM-DD.' + sLineBreak + sLineBreak +
    'INSTRUCCIONES SOBRE CÓDIGOS DE ARTÍCULO:' + sLineBreak +
    '- Cada línea de detalle tiene una columna CÓDIGO o REFERENCIA. NUNCA la omitas.' + sLineBreak +
    '- El código puede ser numérico (ej: "010193"), alfanumérico (ej: "SPR-001") o un código de barras. Si no hay, usa "".' + sLineBreak + sLineBreak +
    'FORMATO DE RESPUESTA: Devuelve ÚNICAMENTE un objeto JSON (sin markdown ni texto adicional) con esta estructura:' + sLineBreak +
    '{"tipo": "FACTURA", "datos": {' + sLineBreak +
    '  "cif_empresa_destino": "CIF de la empresa compradora registrada: ' + GetEmpresasPromptList(dmgMain.dbConn) + '",' + sLineBreak +
    '  "nombre_empresa_destino": "Razón social de la empresa compradora receptora",' + sLineBreak +
    '  "nif_proveedor": "CIF/NIF del emisor",' + sLineBreak +
    '  "nombre_proveedor": "Razón social completa",' + sLineBreak +
    '  "direccion_proveedor": "Dirección fiscal",' + sLineBreak +
    '  "poblacion_proveedor": "Población",' + sLineBreak +
    '  "cp_proveedor": "Código postal",' + sLineBreak +
    '  "provincia_proveedor": "Provincia",' + sLineBreak +
    '  "telefono_proveedor": "Teléfono",' + sLineBreak +
    '  "numero": "Número de factura",' + sLineBreak +
    '  "fecha": "YYYY-MM-DD",' + sLineBreak +
    '  "base": 0.0,' + sLineBreak +
    '  "iva": 0.0,' + sLineBreak +
    '  "total": 0.0,' + sLineBreak +
    '  "detalles": [' + sLineBreak +
    '    {' + sLineBreak +
    '      "codigo": "Código o referencia del artículo",' + sLineBreak +
    '      "descripcion": "Descripción del producto o servicio",' + sLineBreak +
    '      "bultos": 1.0,' + sLineBreak +
    '      "cantidad_bulto": 1.0,' + sLineBreak +
    '      "cantidad": 1.0,' + sLineBreak +
    '      "precio": 0.0,' + sLineBreak +
    '      "tipo_iva": 10,' + sLineBreak +
    '      "descuento": 0.0,' + sLineBreak +
    '      "descuento_importe": 0.0,' + sLineBreak +
    '      "total": 0.0,' + sLineBreak +
    '      "lote": "Lote si existe",' + sLineBreak +
    '      "fecha_caducidad": "YYYY-MM-DD si existe"' + sLineBreak +
    '    }' + sLineBreak +
    '  ]' + sLineBreak +
    '}}' + sLineBreak + sLineBreak +
    'REGLAS ADICIONALES:' + sLineBreak +
    '- REGLA DE PACKS/BULTOS: Analiza la descripción o columnas en busca de indicaciones de unidades o peso por bulto/caja (ej: "caja-2,5 kg", "6 BRIK X 1 L.", "50u").' + sLineBreak +
    '- DETERMINACIÓN DEL PRECIO UNITARIO Y CANTIDAD: "bultos" es cajas/packs, "cantidad" es bultos * cantidad_bulto. "precio" es el precio unitario individual.' + sLineBreak +
    '- LOTES MÚLTIPLES: Si un artículo desglosa varios lotes o caducidades, genera un objeto independiente en el array "detalles" para cada lote.' + sLineBreak +
    '- IDENTIFICACIÓN EMPRESA DESTINO: Identifica cuál de nuestras empresas receptoras es la compradora y pon su CIF exacto en "cif_empresa_destino".' + sLineBreak +
    '- No inventes datos. Si un campo no es legible, usa cadena vacía "" o 0.';

  try
    JsonText := CallGeminiVision(AFilePath, FullPrompt, ApiKey, Model);
  except
    on E: Exception do
    begin
      AErrorMsg := 'Error al invocar la API de Gemini: ' + E.Message;
      Exit;
    end;
  end;

  JSValue := TJSONObject.ParseJSONValue(JsonText);
  if not Assigned(JSValue) or not (JSValue is TJSONObject) then
  begin
    AErrorMsg := 'La respuesta de la IA no contiene un JSON estructurado válido: ' + JsonText;
    if Assigned(JSValue) then JSValue.Free;
    Exit;
  end;

  MainObj := JSValue as TJSONObject;
  try
    DataObj := MainObj.FindValue('datos') as TJSONObject;
    if not Assigned(DataObj) then
      DataObj := MainObj;

    dmgMain.dbConn.StartTransaction;
    Query := TFDQuery.Create(nil);
    try
      Query.Connection := dmgMain.dbConn;

      // 0. Detectar Empresa Destino según CIF/Razón Social del receptor
      IdEmpresaNum := DetectarEmpresaDestino(Query, DataObj);

      // 1. Buscar o Crear Proveedor
      IdProv := FindOrCreateProveedor(Query, DataObj);

      DocNumero := GetJSONString(DataObj, 'numero', 'S/N');

      // Comprobar Duplicado usando idproveedor e idempresa
      Query.Close;
      Query.SQL.Text := 'SELECT COUNT(*) FROM ge_prov_facturas WHERE documento = :num AND idproveedor = :idprov AND idempresa = :idempresa';
      Query.ParamByName('num').DataType := ftString;
      Query.ParamByName('idprov').DataType := ftInteger;
      Query.ParamByName('idempresa').DataType := ftInteger;
      Query.ParamByName('num').AsString := DocNumero;
      Query.ParamByName('idprov').AsInteger := StrToIntDef(IdProv, 0);
      Query.ParamByName('idempresa').AsInteger := IdEmpresaNum;
      Query.Open;
      if Query.Fields[0].AsInteger > 0 then
      begin
        Query.Close;
        raise Exception.Create('Ya existe una factura registrada con este número (' + DocNumero + ') para este proveedor en la empresa destino.');
      end;
      Query.Close;

      // 2. Insertar Cabecera de la Factura
      Query.SQL.Text := 'INSERT INTO ge_prov_facturas (idempresa, idproveedor, documento, fecha, base, totaliva, totalentrada) ' +
                        'VALUES (:idempresa, :idproveedor, :documento, :fecha, :base, :totaliva, :totalentrada)';
      Query.ParamByName('idempresa').DataType := ftInteger;
      Query.ParamByName('idproveedor').DataType := ftInteger;
      Query.ParamByName('documento').DataType := ftString;
      Query.ParamByName('fecha').DataType := ftDate;
      Query.ParamByName('base').DataType := ftFloat;
      Query.ParamByName('totaliva').DataType := ftFloat;
      Query.ParamByName('totalentrada').DataType := ftFloat;

      Query.ParamByName('idempresa').AsInteger := IdEmpresaNum;
      Query.ParamByName('idproveedor').AsInteger := StrToIntDef(IdProv, 0);
      Query.ParamByName('documento').AsString := DocNumero;
      Query.ParamByName('fecha').AsDate := ISO8601ToDate(GetJSONString(DataObj, 'fecha', DateToStr(Date)));
      Query.ParamByName('base').AsFloat := GetJSONFloat(DataObj, 'base');
      Query.ParamByName('totaliva').AsFloat := GetJSONFloat(DataObj, 'iva');
      Query.ParamByName('totalentrada').AsFloat := GetJSONFloat(DataObj, 'total');
      Query.ExecSQL;

      // Recuperar ID autoincremental
      Query.SQL.Text := 'SELECT LAST_INSERT_ID()';
      Query.Open;
      MasterID := Query.Fields[0].AsInteger;
      Query.Close;

      // 3. Insertar Detalles
      if (DataObj.FindValue('detalles') <> nil) and (DataObj.FindValue('detalles') is TJSONArray) then
      begin
        Details := DataObj.FindValue('detalles') as TJSONArray;
        for I := 0 to Details.Count - 1 do
        begin
          DetObj := Details.Items[I] as TJSONObject;

          LCant := GetJSONFloat(DetObj, 'cantidad');
          LPrec := GetJSONFloat(DetObj, 'precio');
          LBultos := GetJSONFloat(DetObj, 'bultos', 1.0);
          if LBultos <= 0 then LBultos := 1.0;
          LCantBulto := GetJSONFloat(DetObj, 'cantidad_bulto', 1.0);
          if LCantBulto <= 0 then LCantBulto := 1.0;

          // Si el artículo ya existe en ge_proveedores_materias_primas, usar cantidad_por_bulto registrada
          Query.Close;
          Query.SQL.Text := 'SELECT cantidad_por_bulto FROM ge_proveedores_materias_primas ' +
                            'WHERE id_proveedor = :idprov AND codigo_articulo_proveedor = :cod LIMIT 1';
          Query.ParamByName('idprov').DataType := ftInteger;
          Query.ParamByName('idprov').AsInteger := StrToIntDef(IdProv, 0);
          Query.ParamByName('cod').DataType := ftString;
          Query.ParamByName('cod').AsString := GetJSONString(DetObj, 'codigo', '');
          Query.Open;
          if not Query.Eof and not Query.Fields[0].IsNull then
          begin
            RegisteredCantBulto := Query.Fields[0].AsFloat;
            if RegisteredCantBulto > 0 then
            begin
              DocPrice := LPrec * LCantBulto;
              LCantBulto := RegisteredCantBulto;
              LCant := LBultos * LCantBulto;
              LPrec := DocPrice / LCantBulto;
            end;
          end;
          Query.Close;

          LDesc := GetJSONFloat(DetObj, 'descuento');
          LDescAbs := GetJSONFloat(DetObj, 'descuento_importe');
          LIva  := GetJSONInt(DetObj, 'tipo_iva');

          // Calcular descuentos mutuos
          if (LDescAbs <> 0) and (LDesc = 0) then
          begin
            if LCant > 0 then
              LDescAbs := -Abs(LDescAbs / LCant)
            else
              LDescAbs := -Abs(LDescAbs);

            if LPrec > 0 then
              LDesc := (Abs(LDescAbs) / LPrec) * 100
            else
              LDesc := 0;
          end
          else if (LDesc <> 0) then
          begin
            LDescAbs := -Abs(LPrec * LDesc / 100);
          end
          else
          begin
            LDescAbs := 0;
            LDesc := 0;
          end;

          LBase := LCant * (LPrec + LDescAbs);
          LTot  := LBase * (1 + (LIva / 100));

          Query.SQL.Text := 'INSERT INTO ge_prov_facturas_detalle (idempresa, idfactura, idproveedor, codigo, descripcion, ' +
                            'lote, bultos, cantidad_bulto, cantidad, precio, tipo_iva, base, total, fecha_caducidad, descuento_porcentaje, descuento_precio) ' +
                            'VALUES (:idempresa, :idfactura, :idproveedor, :codigo, :descripcion, :lote, :bultos, :cantidad_bulto, :cantidad, :precio, :tipo_iva, :base, :total, :fecha_caducidad, :descuento_porcentaje, :descuento_precio)';

          Query.ParamByName('idempresa').DataType := ftInteger;
          Query.ParamByName('idfactura').DataType := ftInteger;
          Query.ParamByName('idproveedor').DataType := ftInteger;
          Query.ParamByName('codigo').DataType := ftString;
          Query.ParamByName('descripcion').DataType := ftString;
          Query.ParamByName('lote').DataType := ftString;
          Query.ParamByName('bultos').DataType := ftFloat;
          Query.ParamByName('cantidad_bulto').DataType := ftFloat;
          Query.ParamByName('cantidad').DataType := ftFloat;
          Query.ParamByName('precio').DataType := ftFloat;
          Query.ParamByName('tipo_iva').DataType := ftInteger;
          Query.ParamByName('base').DataType := ftFloat;
          Query.ParamByName('total').DataType := ftFloat;
          Query.ParamByName('descuento_porcentaje').DataType := ftFloat;
          Query.ParamByName('descuento_precio').DataType := ftFloat;
          Query.ParamByName('fecha_caducidad').DataType := ftDate;

          Query.ParamByName('idempresa').AsInteger := IdEmpresaNum;
          Query.ParamByName('idfactura').AsInteger := MasterID;
          Query.ParamByName('idproveedor').AsInteger := StrToIntDef(IdProv, 0);
          Query.ParamByName('codigo').AsString := GetJSONString(DetObj, 'codigo', '');
          DescStr := GetJSONString(DetObj, 'descripcion', 'Sin descripción');
          Query.ParamByName('descripcion').AsString := DescStr;

          // Lote
          LoteStr := Trim(GetJSONString(DetObj, 'lote', ''));
          if (LoteStr = '') or (LoteStr = 'null') then
          begin
            if TRegEx.IsMatch(DescStr, 'LOTE[:\s]*([\w\-\.]+)', [roIgnoreCase]) then
              LoteStr := TRegEx.Match(DescStr, 'LOTE[:\s]*([\w\-\.]+)', [roIgnoreCase]).Groups[1].Value;
          end;
          if (LoteStr = '') or (LoteStr = 'null') then
            LoteStr := DocNumero;

          Query.ParamByName('lote').AsString := LoteStr;
          Query.ParamByName('bultos').AsFloat := LBultos;
          Query.ParamByName('cantidad_bulto').AsFloat := LCantBulto;
          Query.ParamByName('cantidad').AsFloat := LCant;
          Query.ParamByName('precio').AsFloat := LPrec;
          Query.ParamByName('tipo_iva').AsInteger := LIva;
          Query.ParamByName('base').AsFloat := LBase;
          Query.ParamByName('total').AsFloat := LTot;
          Query.ParamByName('descuento_porcentaje').AsFloat := LDesc;
          Query.ParamByName('descuento_precio').AsFloat := LDescAbs;

          CadStr := GetJSONString(DetObj, 'fecha_caducidad', '');
          if (CadStr <> '') and (CadStr <> 'null') then
            Query.ParamByName('fecha_caducidad').AsDate := ISO8601ToDate(CadStr)
          else
            Query.ParamByName('fecha_caducidad').Value := Null;

          Query.ExecSQL;
          CheckAndInsertProveedorMateriaPrima(Query, StrToIntDef(IdProv, 0), GetJSONString(DetObj, 'codigo', ''), DescStr, LPrec, LCantBulto);
        end;
      end;

      // 4. Guardar archivo original escaneado en ge_documentos
      NewDocName := SanitizeForFileName(
        GetJSONString(DataObj, 'fecha', DateToStr(Date)) + '_' +
        SanitizeNIF(GetJSONString(DataObj, 'nif_proveedor', 'XX')) + '_' +
        GetJSONString(DataObj, 'nombre_proveedor', 'XX') + '_' +
        'FAC_' +
        DocNumero
      ) + TPath.GetExtension(AFilePath);

      LinkDocument(dmgMain.dbConn, 'ge_prov_facturas', MasterID, AFilePath, NewDocName, IdEmpresaNum);

      dmgMain.dbConn.Commit;
      AIdFacturaGenerada := MasterID;
      Result := True;
    finally
      Query.Free;
    end;
  finally
    JSValue.Free;
  end;
end;

end.
