/*
 * Copyright 2021-2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.opentest4j.reporting.cli;

import org.apiguardian.api.API;
import org.opentest4j.reporting.tooling.core.htmlreport.DefaultHtmlReportWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;

import java.awt.*;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.Callable;

import static org.apiguardian.api.API.Status.EXPERIMENTAL;

/**
 * Converts from the event-based to the hierarchical XML format.
 *
 * @since 0.2.0
 */
@Command(name = "html-report", description = "Creates an HTML report from a event-based or hierarchical XML file")
@API(status = EXPERIMENTAL, since = "0.2.0")
public class HtmlReportCommand implements Callable<Integer> {

	private static final Logger LOG = LoggerFactory.getLogger(HtmlReportCommand.class);

	@Parameters(arity = "1..*", description = "The XML file(s) to convert")
	List<Path> xmlFiles;

	@Option(names = { "-o", "--output" }, description = "The target HTML file")
	Path targetFile;

	@Option(names = "--open", description = "Open the generated HTML report in the default browser")
	boolean open;

	// Make constructor package-private
	HtmlReportCommand() {
	}

	@Override
	public Integer call() throws Exception {
		if (targetFile == null) {
			var firstXmlFile = xmlFiles.get(0);
			var sourceFileName = firstXmlFile.getFileName().getFileName().toString();
			var targetFileName = (sourceFileName.endsWith(".xml")
					? sourceFileName.substring(0, sourceFileName.length() - 4)
					: sourceFileName) + ".html";
			targetFile = firstXmlFile.resolveSibling(targetFileName);
		}

		new DefaultHtmlReportWriter().writeHtmlReport(xmlFiles, targetFile);

		LOG.info("Wrote HTML report to {}", targetFile.toUri());
		if (open) {
			LOG.info("Opening HTML report in default browser...");
			Desktop.getDesktop().browse(targetFile.toUri());
		}
		return 0;
	}
}
