//
//  Analytics.swift
//
//
//  Created by Loris Perret on 08/12/2023.
//

import ArgumentParser
import Foundation
import ToolCore

struct Analytics: ParsableCommand {

    // MARK: - Command Configuration

    static let configuration = CommandConfiguration(
        abstract: "Generate analytics extension file.",
        version: ResgenSwiftVersion
    )

    // MARK: - Static

    static let toolName = "Analytics"
    static let defaultExtensionName = "Analytics"

    // MARK: - Command Options

    @OptionGroup var options: AnalyticsOptions

    // MARK: - Run

    mutating func run() {
        print("[\(Self.toolName)] Starting analytics generation")
        print("[\(Self.toolName)] Will use inputFile \(options.inputFile) to generate analytics for target: \(options.target)")

        // Check requirements
        guard checkRequirements() else { return }

        print("[\(Self.toolName)] Will generate analytics")

        // Parse input file
        let sections = AnalyticsFileParser().parse(options.inputFile, target: options.target)

        // Generate extension
        AnalyticsGenerator.writeExtensionFiles(
            sections: sections,
            target: options.target,
            tags: ["ios", "iosonly"],
            isStatic: options.staticMembers,
            outputFile: options.outputFile,
            visibility: options.extensionVisibility
        )

        print("[\(Self.toolName)] Analytics generated")
    }

    // MARK: - Requirements

    private func checkRequirements() -> Bool {
        let fileManager = FileManager()

        // Input file
        guard fileManager.fileExists(atPath: options.inputFile) else {
            let error = AnalyticsError.fileNotExists(options.inputFile)
            print(error.description)
            Self.exit(withError: error)
        }

        guard TrackerType.hasValidTarget(in: options.target) else {
            let error = AnalyticsError.noValidTracker(options.target)
            print(error.description)
            Self.exit(withError: error)
        }

        // Check if needed to regenerate
        guard GeneratorChecker.shouldGenerate(
            force: options.forceGeneration,
            inputFilePath: options.inputFile,
            extensionFilePath: options.outputFile
        ) else {
            print("[\(Self.toolName)] Analytics are already up to date :) ")
            return false
        }

        return true
    }
}
