/** RandomIMEI QA contract v1.0.0. Browser and CLI use this exact module. */
export const CONTRACT_VERSION = '1.0.0';
export const LIMITS = Object.freeze({ rows: 200, characters: 100000, field: 256 });
export const STATUSES = Object.freeze(['valid', 'body14', 'checksum', 'length', 'characters', 'empty']);
export const INPUT_COLUMNS = Object.freeze(['case_id', 'record_id', 'slot', 'imei', 'expected_status', 'expected_duplicate']);
// Accepted for import compatibility with the main generator's CSV export.
// These descriptive fields do not become validation evidence or expectations.
export const GENERATOR_METADATA_COLUMNS = Object.freeze(['formatted', 'tac', 'serial', 'check_digit', 'profile_family', 'profile_label', 'profile_type', 'profile_release_year', 'mapping_confidence', 'model_identity', 'snapshot_version']);

export class QaInputError extends Error {
    constructor(code) { super(code); this.name = 'QaInputError'; this.code = code; }
}

export function checkDigit(body) {
    if (typeof body !== 'string' || !/^[0-9]{14}$/.test(body)) throw new QaInputError('body');
    let sum = 0;
    for (let i = 0; i < 14; i++) {
        const digit = Number(body[i]) * (i % 2 === 1 ? 2 : 1);
        sum += digit > 9 ? digit - 9 : digit;
    }
    return String((10 - sum % 10) % 10);
}

export function inspect(input) {
    if (typeof input !== 'string') throw new QaInputError('string');
    const normalized = input.replace(/[\s\p{Z}-]+/gu, '');
    const result = {
        input, normalized, status: 'empty', separators_removed: normalized !== input,
        is_valid: false, completed_imei: null, expected_check_digit: null,
    };
    if (!normalized) return result;
    if (!/^[0-9]+$/.test(normalized)) return { ...result, status: 'characters' };
    if (![14, 15].includes(normalized.length)) return { ...result, status: 'length' };
    result.expected_check_digit = checkDigit(normalized.slice(0, 14));
    if (normalized.length === 14) return { ...result, status: 'body14', completed_imei: normalized + result.expected_check_digit };
    result.is_valid = normalized[14] === result.expected_check_digit;
    return { ...result, status: result.is_valid ? 'valid' : 'checksum' };
}

/** Quoted CSV supports commas, escaped quotes and embedded newlines; never coerces numbers. */
export function parseCsv(text) {
    if (typeof text !== 'string') throw new QaInputError('string');
    if (text.length > LIMITS.characters) throw new QaInputError('size');
    const input = text.replace(/^\uFEFF/, '');
    const rows = [];
    let row = [], value = '', quoted = false, closed = false, started = false;
    const finishRow = () => {
        if (started || row.length || value.length) rows.push([...row, value]);
        row = []; value = ''; started = false; closed = false;
        if (rows.length > LIMITS.rows + 1) throw new QaInputError('rows');
    };
    for (let i = 0; i < input.length; i++) {
        const char = input[i];
        if (quoted) {
            if (char === '"') {
                if (input[i + 1] === '"') { value += '"'; i++; }
                else { quoted = false; closed = true; }
            } else value += char;
        } else if (char === ',') {
            row.push(value); value = ''; closed = false; started = true;
        } else if (char === '\n' || char === '\r') {
            if (char === '\r' && input[i + 1] === '\n') i++;
            finishRow();
        } else if (char === '"' && !value.length && !closed) {
            quoted = true; started = true;
        } else {
            if (closed || char === '"') throw new QaInputError('csv');
            value += char; started = true;
        }
        if (value.length > LIMITS.field) throw new QaInputError('field');
    }
    if (quoted) throw new QaInputError('csv');
    finishRow();
    return rows;
}

/** Accept a CSV with an imei header, or one raw string per line. */
export function parseInput(text) {
    const rows = parseCsv(text);
    if (!rows.length) throw new QaInputError('empty');
    const first = rows[0].map(value => value.trim());
    const hasHeader = first.includes('imei');
    if (hasHeader && (new Set(first).size !== first.length || first.some(key => !INPUT_COLUMNS.includes(key) && !GENERATOR_METADATA_COLUMNS.includes(key)))) throw new QaInputError('header');
    if (!hasHeader && rows.some(row => row.length !== 1)) throw new QaInputError('header');
    const data = hasHeader ? rows.slice(1) : rows;
    if (!data.length) throw new QaInputError('empty');
    if (data.length > LIMITS.rows) throw new QaInputError('rows');
    const ids = new Set();
    return data.map((row, index) => {
        if (hasHeader && row.length !== first.length) throw new QaInputError('columns');
        const entry = hasHeader ? Object.fromEntries(first.map((key, i) => [key, row[i]])) : { imei: row[0] };
        const id = entry.case_id || `row-${index + 1}`;
        if (ids.has(id)) throw new QaInputError('ids');
        ids.add(id);
        if (entry.expected_status && !STATUSES.includes(entry.expected_status)) throw new QaInputError('expectation');
        if (entry.expected_duplicate && !['true', 'false'].includes(entry.expected_duplicate)) throw new QaInputError('expectation');
        return {
            case_id: id, record_id: entry.record_id || '', slot: entry.slot || '', imei: entry.imei,
            expected_status: entry.expected_status || null,
            expected_duplicate: entry.expected_duplicate ? entry.expected_duplicate === 'true' : null,
        };
    });
}

export function runReport(text) {
    const entries = parseInput(text);
    const seen = new Map();
    const rows = entries.map((entry, index) => {
        const observed = inspect(entry.imei);
        // Duplicate checks concern complete numeric inputs, even when checksum fails.
        const comparable = /^[0-9]{15}$/.test(observed.normalized);
        const duplicateOf = comparable ? seen.get(observed.normalized) || null : null;
        if (comparable && !duplicateOf) seen.set(observed.normalized, entry.case_id);
        const duplicate = duplicateOf !== null;
        const hasExpected = entry.expected_status !== null || entry.expected_duplicate !== null;
        return {
            row: index + 1, case_id: entry.case_id, record_id: entry.record_id, slot: entry.slot,
            ...observed, duplicate, duplicate_of: duplicateOf,
            expected_status: entry.expected_status, expected_duplicate: entry.expected_duplicate,
            matches_expected: hasExpected ? (entry.expected_status === null || entry.expected_status === observed.status)
                && (entry.expected_duplicate === null || entry.expected_duplicate === duplicate) : null,
        };
    });
    return {
        contract: 'randomimei-qa', contract_version: CONTRACT_VERSION,
        device_lookup: 'not_performed',
        summary: {
            total: rows.length,
            statuses: Object.fromEntries(STATUSES.map(status => [status, rows.filter(row => row.status === status).length])),
            normalized: rows.filter(row => row.separators_removed).length,
            duplicates: rows.filter(row => row.duplicate).length,
            expectations: rows.filter(row => row.matches_expected !== null).length,
            mismatches: rows.filter(row => row.matches_expected === false).length,
        },
        rows,
    };
}

const csvCell = value => `"${String(value ?? '').replaceAll('"', '""')}"`;
export function inputCsv(entries) {
    return [INPUT_COLUMNS.join(','), ...entries.map(entry => INPUT_COLUMNS.map(key => csvCell(entry[key])).join(','))].join('\n') + '\n';
}

/** CSV spreadsheet formula guard; JSON is the lossless report. Import CSV columns as text. */
export function reportCsv(report) {
    const columns = ['row', 'case_id', 'record_id', 'slot', 'input', 'normalized', 'status', 'separators_removed', 'duplicate', 'duplicate_of', 'completed_imei', 'expected_check_digit', 'expected_status', 'expected_duplicate', 'matches_expected'];
    const safe = value => {
        const text = String(value ?? '');
        return /^[\s]*[=+@-]/u.test(text) || /^[\t\r\n]/u.test(text) ? `'${text}` : text;
    };
    return [columns.join(','), ...report.rows.map(row => columns.map(column => csvCell(safe(row[column]))).join(','))].join('\n') + '\n';
}

/** Deterministic fixtures only: FNV-1a UTF-16 seed followed by xorshift32, v1. */
export function generateFixture(seed, scenario = 'mixed') {
    if (typeof seed !== 'string' || !seed.length || seed.length > 100) throw new QaInputError('seed');
    if (!['mixed', 'apple-mdm', 'samsung-inventory'].includes(scenario)) throw new QaInputError('scenario');
    let state = 2166136261;
    for (let i = 0; i < seed.length; i++) state = Math.imul(state ^ seed.charCodeAt(i), 16777619) >>> 0;
    if (!state) state = 0x6d2b79f5;
    const nextDigit = () => {
        state ^= state << 13; state ^= state >>> 17; state ^= state << 5;
        return String((state >>> 0) % 10);
    };
    const complete = () => { const body = Array.from({ length: 14 }, nextDigit).join(''); return body + checkDigit(body); };
    const a = complete(), b = complete();
    const entry = (case_id, imei, expected_status, expected_duplicate = false, record_id = '', slot = '') => ({ case_id, record_id, slot, imei, expected_status, expected_duplicate });
    const separated = `${a.slice(0, 8)}-${a.slice(8)}`;
    if (scenario === 'apple-mdm') return inputCsv([
        entry('mdm-a-imei1', a, 'valid', false, 'mock-apple-a', 'IMEI1'),
        entry('mdm-a-imei2', b, 'valid', false, 'mock-apple-a', 'IMEI2'),
        entry('mdm-b-copied-imei1', separated, 'valid', true, 'mock-apple-b', 'IMEI1'),
        entry('mdm-b-missing-imei2', '', 'empty', false, 'mock-apple-b', 'IMEI2'),
        entry('mdm-c-bad-checksum', b.slice(0, 14) + (Number(b[14]) + 1) % 10, 'checksum', false, 'mock-apple-c', 'IMEI1'),
    ]);
    if (scenario === 'samsung-inventory') return inputCsv([
        entry('inventory-first', a, 'valid', false, 'mock-android-a', 'IMEI1'),
        entry('inventory-repeat', separated, 'valid', true, 'mock-android-b', 'IMEI1'),
        entry('inventory-distinct', b, 'valid', false, 'mock-android-c', 'IMEI1'),
        entry('inventory-leading-zero', '000000000000000', 'valid', false, 'mock-edge-case', 'IMEI1'),
        entry('inventory-bad-checksum', b.slice(0, 14) + (Number(b[14]) + 1) % 10, 'checksum', false, 'mock-negative', 'IMEI1'),
    ]);
    return inputCsv([
        entry('valid', a, 'valid'), entry('bad-checksum', a.slice(0, 14) + (Number(a[14]) + 1) % 10, 'checksum'),
        entry('body14', a.slice(0, 14), 'body14'), entry('short', '123', 'length'),
        entry('letters', '49015420A237518', 'characters'), entry('separators-and-duplicate', separated, 'valid', true),
        entry('leading-zeros', '000000000000000', 'valid'), entry('missing', '', 'empty'),
        entry('unicode-digits', '４９０１５４２０３２３７５１８', 'characters'), entry('another-valid', b, 'valid'),
    ]);
}
