import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import handlebars from 'handlebars';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

let partialsRegistered = false;

/** Resolve partials folder for both `tsx src/...` and `node dist/src/...` layouts. */
/** Inline logo so emails and preview work without public URLs or CID attachments. */
function resolveEmailHeaderLogoPath(partialsDir: string): string | null {
    const candidates = [
        path.join(partialsDir, '..', 'Re_Logo.png'),
        path.join(process.cwd(), 'src/emailtemplates/Re_Logo.png'),
        path.join(process.cwd(), 'Dealer_Onboarding_Backend/src/emailtemplates/Re_Logo.png'),
        path.join(__dirname, '../../emailtemplates/Re_Logo.png'),
        path.join(__dirname, '../../../../src/emailtemplates/Re_Logo.png')
    ];
    for (const p of candidates) {
        if (fs.existsSync(p)) return p;
    }
    return null;
}

function injectEmailHeaderLogo(html: string, partialsDir: string): string {
    const logoPath = resolveEmailHeaderLogoPath(partialsDir);
    if (!logoPath) {
        console.warn('[handlebars-email] Re_Logo.png not found; email header will omit image.');
        return html.replace(
            /<img[^>]*src="__EMAIL_HEADER_LOGO_SRC__"[^>]*>/i,
            '<span style="color:#e31837;font-size:22px;font-weight:bold;letter-spacing:0.05em;">Royal Enfield</span>'
        );
    }
    const b64 = fs.readFileSync(logoPath).toString('base64');
    const dataUri = `data:image/png;base64,${b64}`;
    return html.replace(/__EMAIL_HEADER_LOGO_SRC__/g, dataUri);
}

function resolveEmailPartialsDir(): string {
    const marker = 'email_header.html';
    const candidates = [
        path.join(__dirname, '../../emailtemplates/partials'),
        path.join(__dirname, '../../../../src/emailtemplates/partials'),
        path.join(process.cwd(), 'src/emailtemplates/partials'),
        path.join(process.cwd(), 'Dealer_Onboarding_Backend/src/emailtemplates/partials')
    ];
    for (const dir of candidates) {
        if (fs.existsSync(path.join(dir, marker))) return dir;
    }
    console.warn('[handlebars-email] Could not resolve emailtemplates/partials; tried:', candidates);
    return candidates[0];
}

/** Register shared layout & CTA partials (idempotent). */
export function registerEmailPartials(h: typeof handlebars = handlebars): void {
    if (partialsRegistered) return;

    const partialsDir = resolveEmailPartialsDir();
    const map: Record<string, string> = {
        email_header: 'email_header.html',
        email_footer: 'email_footer.html',
        primary_cta: 'primary_cta.html',
        cta_button: 'primary_cta.html'
    };

    let loaded = 0;
    for (const [name, file] of Object.entries(map)) {
        const filePath = path.join(partialsDir, file);
        if (fs.existsSync(filePath)) {
            let src = fs.readFileSync(filePath, 'utf-8');
            if (name === 'email_header') {
                src = injectEmailHeaderLogo(src, partialsDir);
            }
            h.registerPartial(name, src);
            loaded++;
        } else {
            console.warn(`[handlebars-email] Missing partial file: ${filePath}`);
        }
    }

    if (loaded === Object.keys(map).length) {
        partialsRegistered = true;
    } else {
        console.error(
            `[handlebars-email] Only ${loaded}/${Object.keys(map).length} partials loaded from ${partialsDir}`
        );
    }
}

/** Normalize CTA fields for templates using {{> primary_cta}} — URLs come from backend placeholders only. */
export function normalizeCtaPlaceholders(replacements: Record<string, string>): Record<string, string> {
    const ctaUrl =
        replacements.ctaUrl ||
        replacements.link ||
        replacements.portalLink ||
        replacements.actionUrl ||
        '';

    const ctaLabel = replacements.ctaLabel || 'View details';
    const recipientName = (replacements.recipientName || '').trim() || 'Team Member';

    return {
        ...replacements,
        ctaUrl,
        ctaLabel,
        recipientName
    };
}
