/*
Copyright 2026 Seekra

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

    http://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.
*/

import { exists, isDirectory } from './fileAccess.js';
import { cp, mkdir, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';

const logWithName = function logWithName (message, name, loggingFunction = console.log) {
    if (name) loggingFunction(`Artifact '${name}': ${message}`);
    else loggingFunction(message);
};

const validateArtifact = function validateArtifact (artifact) {
    if (typeof artifact.path !== 'string') return false;
    if (artifact.type === 'text') {
        if (!artifact.options) return false;
        return (
            typeof artifact.options.content === 'string' &&
            (
                typeof artifact.options.encoding === 'string' ||
                !Object.hasOwn(artifact.options.encoding, 'encoding')
            )
        );
    } else if (artifact.type === 'copy') {
        if (!artifact.options) return true;
        else if (Object.hasOwn(artifact.options), 'source') {
            return typeof artifact.options.source === 'string';
        } else return true;
    }
};

export const processArtifact = async function processArtifact (artifact, { srcBase = '.', distBase = '.' } = {}) {
    if (!validateArtifact(artifact)) {
        logWithName('Skipping artifact as it is invalid.', artifact.name, console.warn);
        return;
    }
    const distPath = join(distBase, artifact.path);
    const distPathDirectory = dirname(distPath);
    if (!await exists(distPathDirectory)) {
        await mkdir(distPathDirectory, { recursive: true });
    }
    if (artifact.type === 'text') {
        await writeFile(
            distPath,
            artifact.options.content,
            {
                encoding: artifact.options.encoding ?? 'utf-8'
            }
        );
        logWithName(`Wrote to ${distPath}`, artifact.name);
    } else if (artifact.type === 'copy') {
        const srcPath = join(
            srcBase,
            artifact.options
                ? (artifact.options.source ?? artifact.path)
                : artifact.path
        );
        await cp(
            srcPath,
            distPath,
            {
                recursive: true,
                force: true
            }
        );
        logWithName(`Copied ${srcPath} -> ${distPath}`, artifact.name);
    }
};