//
//  File.swift
//  
//
//  Created by Ana Centea on 16.07.2024.
//

import Foundation

public class Repository {
    public let workingTreeDirectory: URL

    public init(workingTreeUrl workingTreeDirectoryUrl: URL) {
        self.workingTreeDirectory = workingTreeDirectoryUrl
    }
}

extension Repository {
    // MARK: Graphite Builder
    func updateGraphiteState(fromBuilder builder: GraphiteRepositoryBuilder, initialize: Bool = false) throws {
        let repoDir = workingTreeDirectory
        let baseDir = workingTreeDirectory.deletingLastPathComponent()
        var commands = ["#!/bin/sh"]
        commands.append("cd \"\(repoDir.path)\"")
        if initialize {
            commands.append("gt init --trunk=\(builder.mainBranch) --no-interactive")
        }
        commands.append(contentsOf: builder.commands)
        
        let contents = commands.joined(separator: "\n").data(using: .utf8)
        
        let script = baseDir.appendingPathComponent("update_graphite.sh")
        FileManager.default.createFile(atPath: script.path, contents: contents, attributes: [.posixPermissions: 0x755])
        
        var env = ProcessInfo.processInfo.environment
        if let path = env["PATH"] {
            env["PATH"] = "/usr/local/bin:/opt/homebrew/bin:".appending(path)
        }
        
        let task = Process()
        task.environment = env
        task.currentDirectoryURL = repoDir
        task.executableURL = script
        task.launch()
        task.waitUntilExit()
    }
    
    public func setupGraphiteState(mainBranch: String = "main", block: (GraphiteRepositoryBuilder) -> Void) throws {
        let builder = GraphiteRepositoryBuilder()
        builder.mainBranch = mainBranch
        block(builder)
        try updateGraphiteState(fromBuilder: builder, initialize: true)
    }
    
    public func updateGraphiteState(block: (GraphiteRepositoryBuilder) -> Void) throws {
        let builder = GraphiteRepositoryBuilder()
        block(builder)
        try updateGraphiteState(fromBuilder: builder, initialize: false)
    }
}
