package com.reallinkbilling.print;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.rowset.serial.SerialBlob;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;

public class BillPdfAttachmentGenerator {

	private static final int CONNECT_TIMEOUT_MS = 20000;
	private static final int READ_TIMEOUT_MS = 30000;

	private BillPdfAttachmentGenerator() {
	}

	public static byte[] fetchBillPdfFromCurrentSession(String actionName, String key, String billNumber, String billDateTime,
			String typeOfBill, String billType, String language) throws IOException {

		HttpServletRequest request = ServletActionContext.getRequest();
		if (request == null) {
			throw new IOException("Unable to read request context for bill PDF generation.");
		}

		HttpSession session = request.getSession(false);
		String sessionId = session != null ? session.getId() : null;

		String query = buildQuery(key, billNumber, billDateTime, typeOfBill, billType, language);
		String baseUrl = buildBaseUrl(request);
		URL url = URI.create(baseUrl + actionName + "?" + query).toURL();

		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
		connection.setReadTimeout(READ_TIMEOUT_MS);
		connection.setDoInput(true);

		if (sessionId != null && !sessionId.trim().isEmpty()) {
			connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
		}

		int responseCode = connection.getResponseCode();
		if (responseCode != HttpURLConnection.HTTP_OK) {
			throw new IOException("Failed to generate bill PDF. HTTP status: " + responseCode);
		}

		byte[] bytes;
		try (InputStream inputStream = connection.getInputStream();
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

			byte[] buffer = new byte[4096];
			int read;
			while ((read = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, read);
			}
			bytes = outputStream.toByteArray();
		}

		if (!isPdf(bytes)) {
			throw new IOException("Generated content is not a valid PDF. contentType="
					+ connection.getContentType() + ", responseCode=" + responseCode + ", sourceUrl=" + url
					+ ", preview=" + preview(bytes));
		}

		return bytes;
	}

	public static byte[] fetchBillPdfWithoutSessionKey(String encodedKey) throws IOException {
		return fetchBillPdfWithoutSessionKey(encodedKey, null);
	}

	public static byte[] fetchBillPdfWithoutSessionKey(String encodedKey, String forcedBillType) throws IOException {
		if (encodedKey == null || encodedKey.trim().isEmpty()) {
			throw new IOException("Missing key for printBillWithOutSession.");
		}

		String decodedKey = URLDecoder.decode(encodedKey, "UTF-8");
		if (decodedKey.toLowerCase().endsWith("pdf")) {
			decodedKey = decodedKey.substring(0, decodedKey.length() - 3);
		}
		String[] keyDetails = decodedKey.split("\\.");
		if (keyDetails.length < 6) {
			throw new IOException("Invalid key format for printBillWithOutSession.");
		}

		String billNumber = decryptWithoutSessionKeyPart(keyDetails[0]);
		String size = decryptWithoutSessionKeyPart(keyDetails[1]);
		String lang = decryptWithoutSessionKeyPart(keyDetails[2]);
		String typeOfBill = decryptWithoutSessionKeyPart(keyDetails[3]);
		String shopId = decryptWithoutSessionKeyPart(keyDetails[4]);
		String shopCode = decryptWithoutSessionKeyPart(keyDetails[5]);
		prepareSessionContextForWithoutSessionPrint(shopId, shopCode);

		String legacyKey = EncryptionDecryption.encrypt(billNumber + "#" + shopId + "#" + shopCode);
		String normalizedSize = normalizePdfSizeOrNull(forcedBillType);
		if (normalizedSize == null) {
			HttpServletRequest currentRequest = ServletActionContext.getRequest();
			if (currentRequest != null) {
				normalizedSize = normalizePdfSizeOrNull(currentRequest.getParameter("billType"));
			}
		}
		if (normalizedSize == null) {
			normalizedSize = normalizePdfSize(size);
		}
		String actionName = resolveActionNameByPdfSize(normalizedSize);
		System.out.println("printBillWithOutSession size => keySize: " + size + ", forcedBillType: " + forcedBillType
				+ ", normalizedSize: " + normalizedSize + ", actionName: " + actionName);
		String language = normalizeLanguage(lang);
		String billDateTime = resolveBillDate(shopId, shopCode, typeOfBill, billNumber);

		return fetchBillPdfFromCurrentSession(actionName, legacyKey, billNumber, billDateTime, typeOfBill, normalizedSize, language);
	}

	private static boolean isPdf(byte[] content) {
		if (content == null || content.length < 4) {
			return false;
		}
		int index = 0;
		if (content.length >= 3 && (content[0] & 0xFF) == 0xEF && (content[1] & 0xFF) == 0xBB
				&& (content[2] & 0xFF) == 0xBF) {
			index = 3;
		}
		while (index < content.length && Character.isWhitespace((char) (content[index] & 0xFF))) {
			index++;
		}
		return index + 3 < content.length && content[index] == '%' && content[index + 1] == 'P'
				&& content[index + 2] == 'D' && content[index + 3] == 'F';
	}

	private static String buildQuery(String key, String billNumber, String billDateTime, String typeOfBill, String billType,
			String language) throws IOException {
		StringBuilder queryBuilder = new StringBuilder();

		if (key != null && !key.trim().isEmpty()) {
			appendQuery(queryBuilder, "key", key);
			appendQuery(queryBuilder, "billNumber", billNumber);
			appendQuery(queryBuilder, "billDateTime", billDateTime);
			appendQuery(queryBuilder, "typeOfBill", typeOfBill);
		} else {
			appendQuery(queryBuilder, "billNumber", billNumber);
			appendQuery(queryBuilder, "billDateTime", billDateTime);
			appendQuery(queryBuilder, "typeOfBill", typeOfBill);
		}

		appendQuery(queryBuilder, "billType", billType);
		appendQuery(queryBuilder, "language", language);
		return queryBuilder.toString();
	}

	private static void appendQuery(StringBuilder queryBuilder, String key, String value) throws IOException {
		if (value == null || value.trim().isEmpty()) {
			return;
		}
		if (queryBuilder.length() > 0) {
			queryBuilder.append("&");
		}
		queryBuilder.append(URLEncoder.encode(key, "UTF-8"));
		queryBuilder.append("=");
		queryBuilder.append(URLEncoder.encode(value, "UTF-8"));
	}

	private static String buildBaseUrl(HttpServletRequest request) {
		String scheme = request.getScheme();
		String server = request.getServerName();
		int port = request.getServerPort();

		boolean defaultPort = ("http".equalsIgnoreCase(scheme) && port == 80)
				|| ("https".equalsIgnoreCase(scheme) && port == 443);
		String portPart = defaultPort ? "" : ":" + port;

		return scheme + "://" + server + portPart + request.getContextPath() + "/";
	}

	private static String normalizeLanguage(String lang) {
		if (lang == null || lang.trim().isEmpty()) {
			return "ENGLISH";
		}
		if ("eng".equalsIgnoreCase(lang) || "english".equalsIgnoreCase(lang)) {
			return "ENGLISH";
		}
		return "MARATHI";
	}

	private static String normalizePdfSize(String size) {
		String resolved = normalizePdfSizeOrNull(size);
		return resolved != null ? resolved : "A5";
	}

	private static String normalizePdfSizeOrNull(String size) {
		if (size == null || size.trim().isEmpty()) {
			return null;
		}
		String normalized = size.trim().toUpperCase().replace(" ", "_");
		if ("A4".equals(normalized)) {
			return "A4";
		}
		if ("A5".equals(normalized)) {
			return "A5";
		}
		if ("THERMAL".equals(normalized) || "THARMAL".equals(normalized)) {
			return "THERMAL";
		}
		return null;
	}

	private static String resolveActionNameByPdfSize(String normalizedSize) {
		if ("A4".equalsIgnoreCase(normalizedSize)) {
			return "billPrintOnly";
		}
		if ("THERMAL".equalsIgnoreCase(normalizedSize)) {
			return "billThermalPrintOnly";
		}
		return "billPrintOnlyType2";
	}

	private static String decryptWithoutSessionKeyPart(String encryptedPart) {
		if (encryptedPart == null) {
			return null;
		}
		String normalizedEncryptedPart = decodeKeyPartIfRequired(encryptedPart);
		try {
			Class<?> clazz = Class.forName("com.reallinkbilling.cipher.EncryptionDecryptionType2");
			Method method = clazz.getMethod("decrypt", String.class);
			Object decrypted = method.invoke(null, normalizedEncryptedPart);
			if (decrypted != null) {
				return String.valueOf(decrypted);
			}
		} catch (Exception e) {
		}
		return EncryptionDecryption.decrypt(normalizedEncryptedPart);
	}

	private static void prepareSessionContextForWithoutSessionPrint(String shopId, String shopCode) throws IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request == null) {
			throw new IOException("Request context unavailable for printBillWithOutSession.");
		}
		HttpSession session = request.getSession(true);
		Object existingShopId = session.getAttribute("shopId");
		Object existingShopCode = session.getAttribute("shopCode");
		Object existingSettings = session.getAttribute("shop_settings");
		if (shopId != null && shopCode != null && shopId.equals(String.valueOf(existingShopId))
				&& shopCode.equals(String.valueOf(existingShopCode)) && existingSettings instanceof Map) {
			return;
		}

		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		String db = "reallinkshop";
		try {
			connection = GetDBConnection.getDBConnection(db);
			session.setAttribute("db", db);
			session.setAttribute("shopId", shopId);
			session.setAttribute("shopCode", shopCode);

			String shopInfoSQL = "SELECT "
					+ "shop_name_english,shop_name_marathi,shop_addressline1_eng,shop_addressline1_mr,"
					+ "message_key,message_sender_id,message_service_provider,shop_name_mr_2,shop_bill_address,"
					+ "customer_care_number,shop_one_line_address,shop_declaration,shop_gst_number,shop_pan_number,"
					+ "head_intro_line_content,shop_type,product_batchcode_based,billing_finanacial_year_date,"
					+ "enable_eway_bill,shop_name_english_estimate_quote "
					+ "FROM shop_info_master WHERE shop_id = ? AND shop_code = ?";
			preparedStatement = connection.prepareStatement(shopInfoSQL);
			preparedStatement.setString(1, shopId);
			preparedStatement.setString(2, shopCode);
			resultSet = preparedStatement.executeQuery();
			if (!resultSet.next()) {
				throw new IOException("Shop not found for printBillWithOutSession key.");
			}
			session.setAttribute("shopnameenglish", resultSet.getString(1));
			session.setAttribute("shopnamemarathi", resultSet.getString(2));
			session.setAttribute("shopaddresseng", resultSet.getString(3));
			session.setAttribute("shopaddressmr", resultSet.getString(4));
			session.setAttribute("message_key", resultSet.getString(5));
			session.setAttribute("message_sender_id", resultSet.getString(6));
			session.setAttribute("serviceprovider", resultSet.getString(7));
			session.setAttribute("shopname2", resultSet.getString(8));
			session.setAttribute("shopbillAddress", resultSet.getString(9));
			session.setAttribute("shopcustcarenumber", resultSet.getString(10));
			session.setAttribute("shoponelineaddress", resultSet.getString(11));
			session.setAttribute("shopdeclaration", resultSet.getString(12));
			session.setAttribute("shopgstnumber", resultSet.getString(13));
			session.setAttribute("shoppannumber", resultSet.getString(14));
			session.setAttribute("headintroline", resultSet.getString(15));
			session.setAttribute("shoptype", resultSet.getString(16));
			session.setAttribute("batchbased", resultSet.getString(17));
			session.setAttribute("financialyearstartdate", resultSet.getString(18));
			session.setAttribute("enableewaybill", resultSet.getString(19));
			session.setAttribute("shopnameenglishestiquote", resultSet.getString(20));
			closeQuietly(resultSet);
			closeQuietly(preparedStatement);

			String settingsSQL = "SELECT setting_name, setting_value FROM shop_settings WHERE shop_id = ? AND shop_code = ?";
			preparedStatement = connection.prepareStatement(settingsSQL);
			preparedStatement.setString(1, shopId);
			preparedStatement.setString(2, shopCode);
			resultSet = preparedStatement.executeQuery();
			HashMap<String, String> shopSettingsMap = new HashMap<String, String>();
			while (resultSet.next()) {
				shopSettingsMap.put(resultSet.getString(1), resultSet.getString(2));
			}
			session.setAttribute("shop_settings", shopSettingsMap);
			session.setAttribute("sendWhatsAppMessage", shopSettingsMap.get("sendWhatsAppMessage"));
			session.setAttribute("defaultWhatsAppNumber", shopSettingsMap.get("defaultWhatsAppNumber"));
			closeQuietly(resultSet);
			closeQuietly(preparedStatement);

			String taxSQL = "SELECT id_tax_table,tax_name FROM shop_tax_table_master WHERE shop_id = ? AND shop_code = ? ORDER BY tax_name";
			preparedStatement = connection.prepareStatement(taxSQL);
			preparedStatement.setString(1, shopId);
			preparedStatement.setString(2, shopCode);
			resultSet = preparedStatement.executeQuery();
			Map<String, String> taxList = new LinkedHashMap<String, String>();
			while (resultSet.next()) {
				taxList.put(resultSet.getString(1), resultSet.getString(2));
			}
			session.setAttribute("tax_list", taxList);
			closeQuietly(resultSet);
			closeQuietly(preparedStatement);

			String bankSQL = "SELECT shop_banking_name,bank_name,bank_branch_name,account_number,IFSC_code,micr_code,upi_id "
					+ "FROM shop_bank_details_master WHERE shop_id = ? AND shop_code = ?";
			preparedStatement = connection.prepareStatement(bankSQL);
			preparedStatement.setString(1, shopId);
			preparedStatement.setString(2, shopCode);
			resultSet = preparedStatement.executeQuery();
			Map<String, String> bankDetails = new LinkedHashMap<String, String>();
			if (resultSet.next()) {
				bankDetails.put("bankingname", resultSet.getString(1));
				bankDetails.put("bankname", resultSet.getString(2));
				bankDetails.put("branchname", resultSet.getString(3));
				bankDetails.put("accnumber", resultSet.getString(4));
				bankDetails.put("ifsccode", resultSet.getString(5));
				bankDetails.put("micrcode", resultSet.getString(6));
				bankDetails.put("upicode", resultSet.getString(7));
			}
			session.setAttribute("bank_details", bankDetails);
			closeQuietly(resultSet);
			closeQuietly(preparedStatement);

			String imageSQL = "SELECT qr_code_file,left_logo_file,right_logo_file,thermal_print_image_file "
					+ "FROM shop_info_master WHERE shop_id = ? AND shop_code = ?";
			preparedStatement = connection.prepareStatement(imageSQL);
			preparedStatement.setString(1, shopId);
			preparedStatement.setString(2, shopCode);
			resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				Blob qrBlob = resultSet.getBlob(1);
				if (qrBlob != null) {
					byte[] qrBytes = readBlobBytes(qrBlob.getBinaryStream());
					if (qrBytes != null) {
						session.setAttribute("qr_image_bolb", new SerialBlob(qrBytes));
					}
					qrBlob.free();
				}
				session.setAttribute("left_logo_image_array", readBlobBytes(resultSet.getBinaryStream(2)));
				session.setAttribute("right_logo_image_array", readBlobBytes(resultSet.getBinaryStream(3)));
				session.setAttribute("thermal_print_header_image", readBlobBytes(resultSet.getBinaryStream(4)));
			}

		} catch (SQLException e) {
			throw new IOException("Failed to prepare session data for printBillWithOutSession.", e);
		} finally {
			closeQuietly(resultSet);
			closeQuietly(preparedStatement);
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
				}
			}
		}
	}

	private static String resolveBillDate(String shopId, String shopCode, String typeOfBill, String billNumber)
			throws IOException {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			connection = GetDBConnection.getDBConnection("reallinkshop");
			String sql = "SELECT DATE_FORMAT(bill_date,'%d-%m-%Y') "
					+ "FROM shop_bill_info_master WHERE shop_id = ? AND shop_code = ? AND bill_number = ? ";
			if (typeOfBill != null && !typeOfBill.trim().isEmpty()) {
				sql += "AND bill_type = ? ";
			}
			sql += "ORDER BY bill_date DESC LIMIT 1";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, shopId);
			preparedStatement.setString(2, shopCode);
			preparedStatement.setString(3, billNumber);
			if (typeOfBill != null && !typeOfBill.trim().isEmpty()) {
				preparedStatement.setString(4, typeOfBill);
			}
			resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				return resultSet.getString(1);
			}
		} catch (SQLException e) {
			throw new IOException("Unable to resolve bill date for printBillWithOutSession.", e);
		} finally {
			closeQuietly(resultSet);
			closeQuietly(preparedStatement);
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
				}
			}
		}
		throw new IOException("Bill date not found for billNumber=" + billNumber + ", billType=" + typeOfBill
				+ ", shopId=" + shopId + ", shopCode=" + shopCode);
	}

	private static byte[] readBlobBytes(InputStream inputStream) throws IOException {
		if (inputStream == null) {
			return null;
		}
		try (InputStream stream = inputStream; ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
			byte[] buffer = new byte[4096];
			int read;
			while ((read = stream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, read);
			}
			return outputStream.toByteArray();
		}
	}

	private static void closeQuietly(ResultSet resultSet) {
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
			}
		}
	}

	private static void closeQuietly(PreparedStatement preparedStatement) {
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
			}
		}
	}

	private static String preview(byte[] content) {
		if (content == null || content.length == 0) {
			return "empty";
		}
		int length = Math.min(content.length, 220);
		String text = new String(content, 0, length, StandardCharsets.UTF_8);
		return text.replaceAll("\\s+", " ").trim();
	}

	private static String decodeKeyPartIfRequired(String encryptedPart) {
		if (encryptedPart == null) {
			return null;
		}
		if (!encryptedPart.startsWith("B64_")) {
			return encryptedPart;
		}
		String payload = encryptedPart.substring(4);
		try {
			byte[] decoded = Base64.getUrlDecoder().decode(payload);
			return new String(decoded, StandardCharsets.UTF_8);
		} catch (IllegalArgumentException e) {
			return encryptedPart;
		}
	}
}
