/*
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 { checkFileReadAccess, exists, isDirectory } from './fileAccess.js';
import { copyFile, mkdir, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';

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

const checkPath = async function checkPath (path) {
    const directory = dirname(path);
    if (await exists(directory) && !await isDirectory(directory)) {
        console.warn('Skipping artifact as parent directory exists and is not a directory.');
        return false;
    } else {
        try {
            if (!await exists(directory)) {
                await mkdir(directory, { recursive: true });
            }
            return true;
        } catch (err) {
            console.warn('Skipping artifact as directory is not creatable.');
            return false;
        }
    }
};

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