/**
 * Spec YAML Parser Service
 *
 * Parses raw YAML strings from spec artifact files into their TypeSpec-generated types.
 * Uses AJV with the generated JSON Schema files for validation, then casts directly
 * to the TypeScript types — no manual field-by-field extraction needed.
 *
 * Lives in the infrastructure layer because it touches node:fs / node:path /
 * node:url / node:crypto and owns the Ajv instance. Application-layer consumers
 * depend on the ISpecArtifactParser port instead of importing this directly.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { injectable } from 'tsyringe';
import Ajv2020 from 'ajv/dist/2020.js';
import addFormats from 'ajv-formats';
import yaml from 'js-yaml';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
/** Resolve the apis/json-schema directory relative to the package root */
function resolveSchemaDir() {
    const currentDir = dirname(fileURLToPath(import.meta.url));
    let dir = currentDir;
    for (let i = 0; i < 10; i++) {
        const candidate = join(dir, 'apis', 'json-schema');
        if (existsSync(candidate))
            return candidate;
        const parent = dirname(dir);
        if (parent === dir)
            break;
        dir = parent;
    }
    throw new Error(`Could not find apis/json-schema directory (searched from ${currentDir})`);
}
/** Recursively strip null values from an object (YAML null → absent key for JSON Schema) */
function stripNulls(obj) {
    if (obj === null || obj === undefined)
        return undefined;
    if (Array.isArray(obj))
        return obj.map(stripNulls);
    if (typeof obj === 'object') {
        const result = {};
        for (const [key, value] of Object.entries(obj)) {
            if (value !== null && value !== undefined) {
                result[key] = stripNulls(value);
            }
        }
        return result;
    }
    return obj;
}
/** Inject default BaseEntity fields if missing */
function injectBaseEntityDefaults(data) {
    const now = new Date().toISOString();
    data.id ??= randomUUID();
    data.createdAt ??= now;
    data.updatedAt ??= now;
}
let SpecYamlParserService = class SpecYamlParserService {
    ajv;
    constructor() {
        this.ajv = new Ajv2020({ allErrors: true, strict: false });
        addFormats(this.ajv);
        const schemaDir = resolveSchemaDir();
        const files = readdirSync(schemaDir).filter((f) => f.endsWith('.yaml'));
        for (const file of files) {
            const content = readFileSync(join(schemaDir, file), 'utf-8');
            const schema = yaml.load(content);
            this.ajv.addSchema(schema, schema.$id);
        }
    }
    validateSchema(schemaId, data) {
        const validate = this.ajv.getSchema(schemaId);
        if (!validate) {
            throw new Error(`Schema not found: ${schemaId}`);
        }
        if (!validate(data)) {
            const errors = validate.errors
                ?.map((e) => `${e.instancePath} ${e.message}`)
                .join('; ');
            throw new Error(`Validation failed for ${schemaId}: ${errors}`);
        }
        return data;
    }
    parseSpecYaml(content) {
        const raw = stripNulls(yaml.load(content));
        injectBaseEntityDefaults(raw);
        return this.validateSchema('FeatureArtifact.yaml', raw);
    }
    parseResearchYaml(content) {
        const raw = stripNulls(yaml.load(content));
        injectBaseEntityDefaults(raw);
        return this.validateSchema('ResearchArtifact.yaml', raw);
    }
    parsePlanYaml(content) {
        const raw = stripNulls(yaml.load(content));
        injectBaseEntityDefaults(raw);
        return this.validateSchema('TechnicalPlanArtifact.yaml', raw);
    }
    parseTasksYaml(content) {
        const raw = stripNulls(yaml.load(content));
        injectBaseEntityDefaults(raw);
        return this.validateSchema('TasksArtifact.yaml', raw);
    }
    parseFeatureStatusYaml(content) {
        const raw = stripNulls(yaml.load(content));
        injectBaseEntityDefaults(raw);
        return this.validateSchema('FeatureStatus.yaml', raw);
    }
};
SpecYamlParserService = __decorate([
    injectable(),
    __metadata("design:paramtypes", [])
], SpecYamlParserService);
export { SpecYamlParserService };
