package com.realnet.OpenAi.Controller;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.realnet.OpenAi.Services.ScriptRunnerService;
import com.realnet.OpenAi.Services.Script_Making;
import com.realnet.OpenAi.Services.SureopsService;
import com.realnet.fnd.response.EntityResponse;

@RestController
@RequestMapping("/sureops")
public class SureOpsController {

	@Value("${projectPath}")
	private String projectpath;
	@Autowired
	private Script_Making script_serviceMaking;

	@Autowired
	private ScriptRunnerService scriptRunnerService;

	@Autowired
	private SureopsService sureopsService;

	@Value("${projectPath}")
	private String projectPath;

	@PostMapping("/deploy")
	public ResponseEntity<?> makeScript(@RequestParam Integer projId, @RequestBody Map<String, String> pageHtmlMap)
			throws IOException, InterruptedException {

		String workflow_id = "56"; // pull script
		int status_code = 500;

		String responsebody = null;

		long Deployment_profile = 2l;
		// NOW MAKE SHELLSCRIPT THAT CLONE FROM REPOSITORY
		ResponseEntity<?> get = script_serviceMaking.CreateFiles(projId, workflow_id, Deployment_profile);

		status_code = get.getStatusCodeValue();
		String filepath = projectPath + File.separator + projId + File.separator + "index";

		if (status_code <= 209) {
			System.out.println(" pull scriopt make");

			if (get.getBody() != null) {

				responsebody = get.getBody().toString().replace("{", "").replace("}", "");

			}
			String filename = "git_pull_exec.sh";

			ResponseEntity<?> script = scriptRunnerService.runScript(filepath, filename);

			if (script.getStatusCodeValue() <= 209) {
				System.out.println(" Run Pull script successfullt now make all file");

				sureopsService.createHtmlFiles(projId, pageHtmlMap);
				System.out.println(" All file created...");

				workflow_id = "58";
				ResponseEntity<?> pushScript = script_serviceMaking.CreateFiles(projId, workflow_id,
						Deployment_profile);
				if (pushScript.getStatusCodeValue() <= 209) {

					String pushScriptfilename = "git_push_exec.sh";

					ResponseEntity<?> scr = scriptRunnerService.runScript(filepath, pushScriptfilename);

					if (scr.getStatusCodeValue() <= 209) {
						System.out.println(" Push Script run successfully");

						System.out.println(" All code successfully push");

						workflow_id = "245";

						ResponseEntity<?> deployScript = script_serviceMaking.CreateFiles(projId, workflow_id,
								Deployment_profile);

						System.out.println("now deploy script make and run");

					}

				}

			}

			return new ResponseEntity<>(new EntityResponse(responsebody), HttpStatus.OK);

		} else {

			if (get.getBody() != null) {

				responsebody = get.getBody().toString().replace("{", "").replace("}", "");

			}

			return new ResponseEntity<>(new EntityResponse(responsebody), HttpStatus.BAD_REQUEST);
		}

	}

	@PostMapping("/SiteTree/createFile")
	public void createHtmlFiles(@RequestParam Integer projId, @RequestBody Map<String, String> pageHtmlMap)
			throws IOException {

		sureopsService.createHtmlFiles(projId, pageHtmlMap);
//		for (Map.Entry<String, String> entry : pageHtmlMap.entrySet()) {
//			String pageName = entry.getKey().trim().replaceAll("\\s+", "_"); // remove spaces from name
//			String htmlContent = entry.getValue();
//
//			String folderPath = projectPath + "/cns-portal/code-extractor/builders/" + projId;
//			File file = new File(folderPath + "/" + pageName + ".html");
//
//			// Ensure directory exists
//			File parentDir = file.getParentFile();
//			if (!parentDir.exists()) {
//				parentDir.mkdirs();
//			}
//
//			// Create new file
//			if (!file.exists()) {
//				file.createNewFile();
//			}
//
//			try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
//				writer.write(htmlContent);
//			}
//
//			System.out.println("✅ File created: " + file.getAbsolutePath());
//		}
	}

	@GetMapping("/run")
	public ResponseEntity<?> runWorkflow(@RequestParam Integer projId, @RequestParam String workflowId)
			throws IOException, InterruptedException {

		int status_code = 500;

		long Deployment_profile = 2l;
		// NOW MAKE SHELLSCRIPT THAT CLONE FROM REPOSITORY
		ResponseEntity<?> get = script_serviceMaking.CreateFiles(projId, workflowId, Deployment_profile);
		return new ResponseEntity<>(new EntityResponse(get.getBody().toString()), HttpStatus.BAD_REQUEST);

	}

}
