# ============================================================
# DELIVERABLE LIFECYCLE MANAGEMENT
# HSEQ Intelligence Dashboard — FASE 1
# Foundation for all service transformations
# ============================================================

import sqlite3
import json
from datetime import datetime
from flask import jsonify, request
from search import get_db, DB_PATH

DELIVERABLE_TYPES = [
    'rie', 'arie', 'mapp', 'training_module', 'toolbox_talk',
    'audit_report', 'inspection_checklist', 'energy_audit',
    'pssr', 'environmental_report', 'capa_action_plan', 'other'
]

DELIVERABLE_SERVICES = ['arbo', 'brzo', 'milieu', 'kam', 'training', 'energy', 'advisor']

STATUS_LABELS = {
    'draft': 'Draft', 'in_review': 'In Review', 'approved': 'Approved',
    'published': 'Published', 'rejected': 'Rejected', 'archived': 'Archived'
}

TYPE_LABELS = {
    'rie': 'RI&E', 'arie': 'ARIE', 'mapp': 'MAPP',
    'training_module': 'Training Module', 'toolbox_talk': 'Toolbox Talk',
    'audit_report': 'Audit Report', 'inspection_checklist': 'Inspection Checklist',
    'energy_audit': 'Energy Audit', 'pssr': 'PSSR',
    'environmental_report': 'Environmental Report',
    'capa_action_plan': 'CAPA Action Plan', 'other': 'Other'
}

SERVICE_LABELS = {
    'arbo': 'Arbo & Veiligheid', 'brzo': 'BRZO / Seveso',
    'milieu': 'Milieu & Omgeving', 'kam': 'KAM Management',
    'training': 'Training & Opleiding', 'energy': 'Energie & Proces',
    'advisor': 'HSEQ Advisor'
}

INTEGRATION_MAP = {
    'training_module': [
        {'target_module': 'module_5', 'target_table': 'elearning_modules', 'action': 'Training module published to eLearning platform'},
        {'target_module': 'module_4', 'target_table': 'training_matrix', 'action': 'Training matrix updated with new module'}
    ],
    'rie': [
        {'target_module': 'module_2', 'target_table': 'risico_scenario', 'action': 'Risicoscenario geupdate in Module 2'}
    ],
    'arie': [
        {'target_module': 'module_2', 'target_table': 'stoffen', 'action': 'Stoffenlijst geupdate in Module 2'},
        {'target_module': 'module_1', 'target_table': 'vbs_elements', 'action': 'VBS elementen geupdate in Module 1'}
    ],
    'audit_report': [
        {'target_module': 'module_5', 'target_table': 'audit_findings', 'action': 'Audit findings opgeslagen in Module 5'},
        {'target_module': 'module_4', 'target_table': 'capa_actions', 'action': 'CAPA actions aangemaakt in Module 4'}
    ],
    'inspection_checklist': [
        {'target_module': 'module_5', 'target_table': 'audit_planning', 'action': 'Inspectie checklist opgenomen in audit planning'}
    ]
}


def init_deliverable_db():
    """Create deliverable lifecycle tables."""
    try:
        conn = sqlite3.connect(DB_PATH)
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS dlv_lifecycle (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            type TEXT NOT NULL,
            service TEXT NOT NULL,
            status TEXT DEFAULT 'draft',
            content TEXT,
            parameters TEXT,
            version INTEGER DEFAULT 1,
            description TEXT,
            created_by TEXT DEFAULT 'system',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            published_at DATETIME,
            parent_id INTEGER,
            module_integration TEXT,
            FOREIGN KEY (parent_id) REFERENCES dlv_lifecycle(id)
        )''')
        c.execute('''CREATE TABLE IF NOT EXISTS dlv_approvals (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            lifecycle_id INTEGER NOT NULL,
            action TEXT NOT NULL,
            reviewer TEXT NOT NULL,
            comment TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (lifecycle_id) REFERENCES dlv_lifecycle(id)
        )''')
        c.execute('''CREATE TABLE IF NOT EXISTS dlv_integrations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            lifecycle_id INTEGER NOT NULL,
            target_module TEXT NOT NULL,
            target_table TEXT,
            target_id INTEGER,
            action TEXT,
            status TEXT DEFAULT 'success',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (lifecycle_id) REFERENCES dlv_lifecycle(id)
        )''')
        c.execute('''CREATE TABLE IF NOT EXISTS safety_maturity_assessments (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            level INTEGER NOT NULL,
            level_name TEXT,
            scores TEXT,
            notes TEXT,
            assessor TEXT DEFAULT 'HSEQ Manager',
            assessed_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )''')
        c.execute('CREATE INDEX IF NOT EXISTS idx_dlv_status ON dlv_lifecycle(status)')
        c.execute('CREATE INDEX IF NOT EXISTS idx_dlv_type ON dlv_lifecycle(type)')
        c.execute('CREATE INDEX IF NOT EXISTS idx_dlv_service ON dlv_lifecycle(service)')
        c.execute('CREATE INDEX IF NOT EXISTS idx_dlvappr ON dlv_approvals(lifecycle_id)')
        c.execute('CREATE INDEX IF NOT EXISTS idx_dlvint ON dlv_integrations(lifecycle_id)')
        conn.commit()
        conn.close()
        print("[OK] Deliverable lifecycle tables initialized")
    except Exception as e:
        print(f"[WARN] init_deliverable_db: {e}")


def _record_approval(lifecycle_id, action, reviewer, comment=None):
    db = get_db()
    db.execute('INSERT INTO dlv_approvals (lifecycle_id, action, reviewer, comment) VALUES (?,?,?,?)',
               (lifecycle_id, action, reviewer, comment))
    db.commit()
    db.close()


def _trigger_integrations(lifecycle_id, dtype):
    integrations = INTEGRATION_MAP.get(dtype, [])
    if not integrations:
        return []
    db = get_db()
    for integ in integrations:
        db.execute(
            'INSERT INTO dlv_integrations (lifecycle_id, target_module, target_table, action, status) VALUES (?,?,?,?,?)',
            (lifecycle_id, integ['target_module'], integ.get('target_table'), integ['action'], 'success')
        )
    db.commit()
    db.close()
    return integrations


def register_deliverable_routes(app, page_fn, BASE_PATH="/hseq-dashboard"):
    """Register all deliverable lifecycle routes."""
    _page = page_fn

    @app.route(BASE_PATH + '/api/deliverables')
    def api_deliverables_list():
        db = get_db()
        try:
            status = request.args.get('status', '')
            dtype = request.args.get('type', '')
            service = request.args.get('service', '')
            sql = 'SELECT * FROM dlv_lifecycle WHERE 1=1'
            params = []
            if status:
                sql += ' AND status = ?'
                params.append(status)
            if dtype:
                sql += ' AND type = ?'
                params.append(dtype)
            if service:
                sql += ' AND service = ?'
                params.append(service)
            sql += ' ORDER BY updated_at DESC'
            rows = db.execute(sql, params).fetchall()
            return jsonify([dict(r) for r in rows])
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/<int:did>')
    def api_deliverable_get(did):
        db = get_db()
        try:
            d = db.execute('SELECT * FROM dlv_lifecycle WHERE id=?', (did,)).fetchone()
            if not d:
                return jsonify({'error': 'Not found'}), 404
            return jsonify(dict(d))
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables', methods=['POST'])
    def api_deliverable_create():
        data = request.get_json(force=True)
        title = data.get('title', '').strip()
        dtype = data.get('type', '')
        service = data.get('service', '')
        if not title or dtype not in DELIVERABLE_TYPES or service not in DELIVERABLE_SERVICES:
            return jsonify({'error': 'Invalid input'}), 400
        db = get_db()
        try:
            content_raw = data.get('content')
            params_raw = data.get('parameters')
            content_json = json.dumps(content_raw) if isinstance(content_raw, (dict, list)) else content_raw
            params_json = json.dumps(params_raw) if isinstance(params_raw, (dict, list)) else params_raw
            cur = db.execute(
                'INSERT INTO dlv_lifecycle (title, type, service, description, content, parameters, created_by) VALUES (?,?,?,?,?,?,?)',
                (title, dtype, service, data.get('description', ''), content_json, params_json, data.get('created_by', 'system'))
            )
            db.commit()
            return jsonify({'id': cur.lastrowid, 'status': 'draft'}), 201
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/<int:did>', methods=['PUT'])
    def api_deliverable_update(did):
        data = request.get_json(force=True)
        db = get_db()
        try:
            d = db.execute('SELECT * FROM dlv_lifecycle WHERE id=?', (did,)).fetchone()
            if not d:
                return jsonify({'error': 'Not found'}), 404
            if d['status'] not in ('draft', 'rejected'):
                return jsonify({'error': 'Can only edit draft/rejected'}), 400
            fields = ['title', 'description', 'content', 'parameters']
            sets, vals = [], []
            for f in fields:
                if f in data:
                    sets.append(f'{f}=?')
                    vals.append(data[f])
            if sets:
                sets.append("updated_at=CURRENT_TIMESTAMP")
                vals.append(did)
                db.execute(f"UPDATE dlv_lifecycle SET {', '.join(sets)} WHERE id=?", vals)
                db.commit()
            return jsonify({'ok': True})
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/<int:did>', methods=['DELETE'])
    def api_deliverable_archive(did):
        db = get_db()
        try:
            d = db.execute('SELECT * FROM dlv_lifecycle WHERE id=?', (did,)).fetchone()
            if not d:
                return jsonify({'error': 'Not found'}), 404
            db.execute("UPDATE dlv_lifecycle SET status='archived', updated_at=CURRENT_TIMESTAMP WHERE id=?", (did,))
            db.commit()
            return jsonify({'ok': True, 'status': 'archived'})
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/<int:did>/submit', methods=['POST'])
    def api_deliverable_submit(did):
        db = get_db()
        try:
            d = db.execute('SELECT * FROM dlv_lifecycle WHERE id=?', (did,)).fetchone()
            if not d:
                return jsonify({'error': 'Not found'}), 404
            if d['status'] != 'draft':
                return jsonify({'error': 'Only draft can be submitted'}), 400
            data = request.get_json(silent=True) or {}
            db.execute("UPDATE dlv_lifecycle SET status='in_review', updated_at=CURRENT_TIMESTAMP WHERE id=?", (did,))
            db.commit()
            _record_approval(did, 'submit_for_review', data.get('reviewer', 'system'), data.get('comment'))
            return jsonify({'ok': True, 'status': 'in_review'})
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/<int:did>/approve', methods=['POST'])
    def api_deliverable_approve(did):
        db = get_db()
        try:
            d = db.execute('SELECT * FROM dlv_lifecycle WHERE id=?', (did,)).fetchone()
            if not d:
                return jsonify({'error': 'Not found'}), 404
            if d['status'] != 'in_review':
                return jsonify({'error': 'Only in_review can be approved'}), 400
            data = request.get_json(silent=True) or {}
            db.execute("UPDATE dlv_lifecycle SET status='approved', updated_at=CURRENT_TIMESTAMP WHERE id=?", (did,))
            db.commit()
            _record_approval(did, 'approve', data.get('reviewer', 'HSEQ Manager'), data.get('comment'))
            return jsonify({'ok': True, 'status': 'approved'})
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/<int:did>/reject', methods=['POST'])
    def api_deliverable_reject(did):
        db = get_db()
        try:
            d = db.execute('SELECT * FROM dlv_lifecycle WHERE id=?', (did,)).fetchone()
            if not d:
                return jsonify({'error': 'Not found'}), 404
            if d['status'] != 'in_review':
                return jsonify({'error': 'Only in_review can be rejected'}), 400
            data = request.get_json(silent=True) or {}
            comment = data.get('comment', 'Geen feedback opgegeven')
            db.execute("UPDATE dlv_lifecycle SET status='rejected', updated_at=CURRENT_TIMESTAMP WHERE id=?", (did,))
            db.commit()
            _record_approval(did, 'reject', data.get('reviewer', 'HSEQ Manager'), comment)
            return jsonify({'ok': True, 'status': 'rejected'})
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/<int:did>/publish', methods=['POST'])
    def api_deliverable_publish(did):
        db = get_db()
        try:
            d = db.execute('SELECT * FROM dlv_lifecycle WHERE id=?', (did,)).fetchone()
            if not d:
                return jsonify({'error': 'Not found'}), 404
            if d['status'] != 'approved':
                return jsonify({'error': 'Only approved can be published'}), 400
            data = request.get_json(silent=True) or {}
            now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
            db.execute("UPDATE dlv_lifecycle SET status='published', published_at=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
                       (now, did))
            db.commit()
            integrations = _trigger_integrations(did, d['type'])
            _record_approval(did, 'publish', data.get('reviewer', 'system'),
                             f"Published. Integrations: {len(integrations)} module(s) updated.")
            return jsonify({'ok': True, 'status': 'published', 'integrations': len(integrations)})
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/<int:did>/revise', methods=['POST'])
    def api_deliverable_revise(did):
        db = get_db()
        try:
            d = db.execute('SELECT * FROM dlv_lifecycle WHERE id=?', (did,)).fetchone()
            if not d:
                return jsonify({'error': 'Not found'}), 404
            if d['status'] != 'rejected':
                return jsonify({'error': 'Only rejected can be revised'}), 400
            data = request.get_json(silent=True) or {}
            new_ver = (d['version'] or 1) + 1
            cur = db.execute(
                'INSERT INTO dlv_lifecycle (title, type, service, status, content, parameters, version, description, created_by, parent_id, module_integration) VALUES (?,?,?,?,?,?,?,?,?,?,?)',
                (d['title'], d['type'], d['service'], 'draft', d['content'], d['parameters'],
                 new_ver, d['description'], data.get('created_by', 'system'), d['id'], d['module_integration'])
            )
            new_id = cur.lastrowid
            db.commit()
            _record_approval(new_id, 'request_revision', data.get('reviewer', 'system'),
                             f"Revised from version {d['version']}")
            return jsonify({'ok': True, 'new_id': new_id, 'version': new_ver, 'status': 'draft'})
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/<int:did>/history')
    def api_deliverable_history(did):
        db = get_db()
        try:
            rows = db.execute(
                'SELECT * FROM dlv_approvals WHERE lifecycle_id=? ORDER BY created_at DESC', (did,)
            ).fetchall()
            return jsonify([dict(r) for r in rows])
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/<int:did>/integrations')
    def api_deliverable_integrations(did):
        db = get_db()
        try:
            rows = db.execute(
                'SELECT * FROM dlv_integrations WHERE lifecycle_id=? ORDER BY created_at DESC', (did,)
            ).fetchall()
            return jsonify([dict(r) for r in rows])
        finally:
            db.close()

    @app.route(BASE_PATH + '/api/deliverables/stats')
    def api_deliverables_stats():
        db = get_db()
        try:
            by_status = db.execute("SELECT status, COUNT(*) as cnt FROM dlv_lifecycle GROUP BY status").fetchall()
            by_type = db.execute("SELECT type, COUNT(*) as cnt FROM dlv_lifecycle GROUP BY type").fetchall()
            by_service = db.execute("SELECT service, COUNT(*) as cnt FROM dlv_lifecycle GROUP BY service").fetchall()
            total = db.execute("SELECT COUNT(*) as cnt FROM dlv_lifecycle").fetchone()['cnt']
            return jsonify({
                'total': total,
                'by_status': {r['status']: r['cnt'] for r in by_status},
                'by_type': {r['type']: r['cnt'] for r in by_type},
                'by_service': {r['service']: r['cnt'] for r in by_service}
            })
        finally:
            db.close()

    # ── UI Page ──

    # @app.route(BASE_PATH + '/deliverables')  # DISABLED: using app.py deliverables management page
    def page_deliverables():
        body = '''
        <div class="page-header" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px">
            <div>
                <h2 style="margin:0;font-size:18px;color:#fff">Deliverable Management</h2>
                <p style="margin:4px 0 0;color:#64748B;font-size:13px">Beheer alle gegenereerde deliverables door de diensten</p>
            </div>
            <button onclick="openNewForm()" style="background:#3B82F6;color:#fff;border:none;padding:8px 20px;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600">+ Nieuwe Deliverable</button>
        </div>
        <div style="display:flex;gap:12px;margin-bottom:16px;flex-wrap:wrap">
            <select id="fStatus" onchange="loadData()" style="background:#1B2A4A;color:#fff;border:1px solid #334155;padding:6px 12px;border-radius:6px;font-size:13px">
                <option value="">Alle Statussen</option>
                <option value="draft">Draft</option><option value="in_review">In Review</option>
                <option value="approved">Approved</option><option value="published">Published</option>
                <option value="rejected">Rejected</option><option value="archived">Archived</option>
            </select>
            <select id="fType" onchange="loadData()" style="background:#1B2A4A;color:#fff;border:1px solid #334155;padding:6px 12px;border-radius:6px;font-size:13px">
                <option value="">Alle Types</option>
                <option value="rie">RI&amp;E</option><option value="arie">ARIE</option>
                <option value="mapp">MAPP</option><option value="training_module">Training Module</option>
                <option value="toolbox_talk">Toolbox Talk</option><option value="audit_report">Audit Report</option>
                <option value="inspection_checklist">Inspection Checklist</option><option value="energy_audit">Energy Audit</option>
                <option value="pssr">PSSR</option><option value="environmental_report">Environmental Report</option>
                <option value="capa_action_plan">CAPA Action Plan</option><option value="other">Other</option>
            </select>
            <select id="fService" onchange="loadData()" style="background:#1B2A4A;color:#fff;border:1px solid #334155;padding:6px 12px;border-radius:6px;font-size:13px">
                <option value="">Alle Diensten</option>
                <option value="arbo">Arbo &amp; Veiligheid</option><option value="brzo">BRZO / Seveso</option>
                <option value="milieu">Milieu &amp; Omgeving</option><option value="kam">KAM Management</option>
                <option value="training">Training &amp; Opleiding</option><option value="energy">Energie &amp; Proces</option>
                <option value="advisor">HSEQ Advisor</option>
            </select>
        </div>
        <div id="stats" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:12px;margin-bottom:20px"></div>
        <div style="overflow-x:auto">
            <table style="width:100%;border-collapse:collapse;font-size:13px">
                <thead><tr style="background:#1B2A4A;text-align:left">
                    <th style="padding:10px 12px;color:#94A3B8;font-weight:600;border-bottom:1px solid #334155">Titel</th>
                    <th style="padding:10px 12px;color:#94A3B8;font-weight:600;border-bottom:1px solid #334155">Type</th>
                    <th style="padding:10px 12px;color:#94A3B8;font-weight:600;border-bottom:1px solid #334155">Dienst</th>
                    <th style="padding:10px 12px;color:#94A3B8;font-weight:600;border-bottom:1px solid #334155">Status</th>
                    <th style="padding:10px 12px;color:#94A3B8;font-weight:600;border-bottom:1px solid #334155">Versie</th>
                    <th style="padding:10px 12px;color:#94A3B8;font-weight:600;border-bottom:1px solid #334155">Aangemaakt</th>
                    <th style="padding:10px 12px;color:#94A3B8;font-weight:600;border-bottom:1px solid #334155">Acties</th>
                </tr></thead>
                <tbody id="tbody"></tbody>
            </table>
        </div>

        <div id="newModal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.6);z-index:200;align-items:center;justify-content:center">
            <div style="background:#0F1D32;border:1px solid #334155;border-radius:12px;padding:28px;width:90%;max-width:560px;max-height:85vh;overflow-y:auto">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px">
                    <h3 style="margin:0;color:#fff;font-size:16px">Nieuwe Deliverable</h3>
                    <button onclick="document.getElementById('newModal').style.display='none'" style="background:none;border:none;color:#94A3B8;font-size:20px;cursor:pointer">&times;</button>
                </div>
                <form id="newForm" onsubmit="createItem(event)">
                    <div style="margin-bottom:14px"><label style="display:block;color:#94A3B8;font-size:12px;margin-bottom:4px">Titel *</label>
                    <input name="title" required style="width:100%;background:#1B2A4A;color:#fff;border:1px solid #334155;padding:8px 12px;border-radius:6px;font-size:13px;box-sizing:border-box"></div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px">
                        <div><label style="display:block;color:#94A3B8;font-size:12px;margin-bottom:4px">Type *</label>
                        <select name="type" required style="width:100%;background:#1B2A4A;color:#fff;border:1px solid #334155;padding:8px 12px;border-radius:6px;font-size:13px;box-sizing:border-box">
                            <option value="">Selecteer...</option>
                            <option value="rie">RI&amp;E</option><option value="arie">ARIE</option><option value="mapp">MAPP</option>
                            <option value="training_module">Training Module</option><option value="toolbox_talk">Toolbox Talk</option>
                            <option value="audit_report">Audit Report</option><option value="inspection_checklist">Inspection Checklist</option>
                            <option value="energy_audit">Energy Audit</option><option value="pssr">PSSR</option>
                            <option value="environmental_report">Environmental Report</option><option value="capa_action_plan">CAPA Action Plan</option>
                            <option value="other">Other</option>
                        </select></div>
                        <div><label style="display:block;color:#94A3B8;font-size:12px;margin-bottom:4px">Dienst *</label>
                        <select name="service" required style="width:100%;background:#1B2A4A;color:#fff;border:1px solid #334155;padding:8px 12px;border-radius:6px;font-size:13px;box-sizing:border-box">
                            <option value="">Selecteer...</option>
                            <option value="arbo">Arbo &amp; Veiligheid</option><option value="brzo">BRZO / Seveso</option>
                            <option value="milieu">Milieu &amp; Omgeving</option><option value="kam">KAM Management</option>
                            <option value="training">Training &amp; Opleiding</option><option value="energy">Energie &amp; Proces</option>
                            <option value="advisor">HSEQ Advisor</option>
                        </select></div>
                    </div>
                    <div style="margin-bottom:14px"><label style="display:block;color:#94A3B8;font-size:12px;margin-bottom:4px">Beschrijving</label>
                    <textarea name="description" rows="2" style="width:100%;background:#1B2A4A;color:#fff;border:1px solid #334155;padding:8px 12px;border-radius:6px;font-size:13px;box-sizing:border-box;resize:vertical"></textarea></div>
                    <div style="margin-bottom:14px"><label style="display:block;color:#94A3B8;font-size:12px;margin-bottom:4px">Content (JSON)</label>
                    <textarea name="content" rows="4" placeholder=\'{"key": "value"}\' style="width:100%;background:#1B2A4A;color:#fff;border:1px solid #334155;padding:8px 12px;border-radius:6px;font-size:12px;box-sizing:border-box;resize:vertical;font-family:monospace"></textarea></div>
                    <div style="margin-bottom:20px"><label style="display:block;color:#94A3B8;font-size:12px;margin-bottom:4px">Parameters (JSON)</label>
                    <textarea name="parameters" rows="3" placeholder=\'{"key": "value"}\' style="width:100%;background:#1B2A4A;color:#fff;border:1px solid #334155;padding:8px 12px;border-radius:6px;font-size:12px;box-sizing:border-box;resize:vertical;font-family:monospace"></textarea></div>
                    <div style="display:flex;gap:10px;justify-content:flex-end">
                        <button type="button" onclick="document.getElementById('newModal').style.display='none'" style="background:#334155;color:#fff;border:none;padding:8px 20px;border-radius:6px;cursor:pointer;font-size:13px">Annuleren</button>
                        <button type="submit" style="background:#3B82F6;color:#fff;border:none;padding:8px 20px;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600">Aanmaken</button>
                    </div>
                </form>
            </div>
        </div>

        <div id="detailModal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.6);z-index:200;align-items:center;justify-content:center">
            <div style="background:#0F1D32;border:1px solid #334155;border-radius:12px;padding:28px;width:90%;max-width:700px;max-height:85vh;overflow-y:auto">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px">
                    <h3 id="dTitle" style="margin:0;color:#fff;font-size:16px"></h3>
                    <button onclick="document.getElementById('detailModal').style.display='none'" style="background:none;border:none;color:#94A3B8;font-size:20px;cursor:pointer">&times;</button>
                </div>
                <div id="dContent"></div>
            </div>
        </div>

        <script>
        const BP="{{BASE_PATH}}";
        const SC={draft:'#6B7280',in_review:'#F59E0B',approved:'#3B82F6',published:'#10B981',rejected:'#EF4444',archived:'#6366F1'};
        const SL={draft:'Draft',in_review:'In Review',approved:'Approved',published:'Published',rejected:'Rejected',archived:'Archived'};
        const TL={rie:'RI&amp;E',arie:'ARIE',mapp:'MAPP',training_module:'Training Module',toolbox_talk:'Toolbox Talk',audit_report:'Audit Report',inspection_checklist:'Inspection Checklist',energy_audit:'Energy Audit',pssr:'PSSR',environmental_report:'Environmental Report',capa_action_plan:'CAPA Action Plan',other:'Other'};
        const SV={arbo:'Arbo &amp; Veiligheid',brzo:'BRZO / Seveso',milieu:'Milieu &amp; Omgeving',kam:'KAM Management',training:'Training &amp; Opleiding',energy:'Energie &amp; Proces',advisor:'HSEQ Advisor'};
        const WF=['draft','in_review','approved','published'];
        function sb(s){return '<span style="display:inline-block;padding:3px 10px;border-radius:12px;font-size:11px;font-weight:600;color:#fff;background:'+(SC[s]||'#6B7280')+'">'+(SL[s]||s)+'</span>';}
        function ab(d){
            let b='';
            if(d.status==='draft')b+='<button onclick="act('+d.id+',\\'submit\\')" style="background:#F59E0B;color:#000;border:none;padding:4px 12px;border-radius:4px;cursor:pointer;font-size:11px;font-weight:600">Submit</button> ';
            if(d.status==='in_review'){b+='<button onclick="act('+d.id+',\\'approve\\')" style="background:#3B82F6;color:#fff;border:none;padding:4px 12px;border-radius:4px;cursor:pointer;font-size:11px;font-weight:600">Approve</button> <button onclick="act('+d.id+',\\'reject\\')" style="background:#EF4444;color:#fff;border:none;padding:4px 12px;border-radius:4px;cursor:pointer;font-size:11px;font-weight:600">Reject</button> ';}
            if(d.status==='approved')b+='<button onclick="act('+d.id+',\\'publish\\')" style="background:#10B981;color:#fff;border:none;padding:4px 12px;border-radius:4px;cursor:pointer;font-size:11px;font-weight:600">Publish</button> ';
            if(d.status==='rejected')b+='<button onclick="act('+d.id+',\\'revise\\')" style="background:#6366F1;color:#fff;border:none;padding:4px 12px;border-radius:4px;cursor:pointer;font-size:11px;font-weight:600">Revise</button> ';
            b+='<button onclick="detail('+d.id+')" style="background:#334155;color:#fff;border:none;padding:4px 12px;border-radius:4px;cursor:pointer;font-size:11px">Detail</button>';
            return b;
        }
        function loadStats(){fetch(BP+'/api/deliverables/stats').then(r=>r.json()).then(s=>{
            document.getElementById('stats').innerHTML=[
                {l:'Totaal',v:s.total,c:'#3B82F6'},{l:'Draft',v:s.by_status.draft||0,c:'#6B7280'},
                {l:'In Review',v:s.by_status.in_review||0,c:'#F59E0B'},{l:'Approved',v:s.by_status.approved||0,c:'#3B82F6'},
                {l:'Published',v:s.by_status.published||0,c:'#10B981'},{l:'Rejected',v:s.by_status.rejected||0,c:'#EF4444'}
            ].map(i=>'<div style="background:#1B2A4A;border-radius:8px;padding:14px;text-align:center;border-left:3px solid '+i.c+'"><div style="font-size:22px;font-weight:700;color:#fff">'+i.v+'</div><div style="font-size:11px;color:#94A3B8;margin-top:2px">'+i.l+'</div></div>').join('');
        });}
        function loadData(){
            let u=BP+'/api/deliverables?';
            const s=document.getElementById('fStatus').value,t=document.getElementById('fType').value,v=document.getElementById('fService').value;
            if(s)u+='status='+s+'&';if(t)u+='type='+t+'&';if(v)u+='service='+v+'&';
            fetch(u).then(r=>r.json()).then(rows=>{
                const tb=document.getElementById('tbody');
                if(!rows.length){tb.innerHTML='<tr><td colspan="7" style="padding:20px;text-align:center;color:#64748B">Geen deliverables gevonden</td></tr>';return;}
                tb.innerHTML=rows.map(d=>'<tr style="border-bottom:1px solid #1B2A4A"><td style="padding:10px 12px;color:#fff;font-weight:500">'+d.title+'</td><td style="padding:10px 12px;color:#94A3B8">'+(TL[d.type]||d.type)+'</td><td style="padding:10px 12px;color:#94A3B8">'+(SV[d.service]||d.service)+'</td><td style="padding:10px 12px">'+sb(d.status)+'</td><td style="padding:10px 12px;color:#94A3B8">v'+d.version+'</td><td style="padding:10px 12px;color:#64748B;font-size:12px">'+(d.created_at?d.created_at.slice(0,10):'-')+'</td><td style="padding:10px 12px">'+ab(d)+'</td></tr>').join('');
            });
        }
        function act(id,a){
            let c=null;if(a==='reject'){c=prompt('Reden voor afwijzing:');if(c===null)return;}
            fetch(BP+'/api/deliverables/'+id+'/'+a,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({comment:c||undefined})}).then(r=>r.json()).then(d=>{if(d.error){alert(d.error);return;}loadData();loadStats();});
        }
        function createItem(e){e.preventDefault();const f=new FormData(e.target);
            fetch(BP+'/api/deliverables',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({title:f.get('title'),type:f.get('type'),service:f.get('service'),description:f.get('description')||'',content:f.get('content')||null,parameters:f.get('parameters')||null})}).then(r=>r.json()).then(d=>{if(d.error){alert(d.error);return;}document.getElementById('newModal').style.display='none';document.getElementById('newForm').reset();loadData();loadStats();});
        }
        function detail(id){
            Promise.all([fetch(BP+'/api/deliverables/'+id).then(r=>r.json()),fetch(BP+'/api/deliverables/'+id+'/history').then(r=>r.json()),fetch(BP+'/api/deliverables/'+id+'/integrations').then(r=>r.json())]).then(([d,h,i])=>{
                document.getElementById('dTitle').textContent=d.title+' (v'+d.version+')';
                let html='<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px">';
                html+='<div style="background:#1B2A4A;padding:12px;border-radius:8px"><span style="color:#64748B;font-size:11px">Type</span><div style="color:#fff;font-size:14px;margin-top:2px">'+(TL[d.type]||d.type)+'</div></div>';
                html+='<div style="background:#1B2A4A;padding:12px;border-radius:8px"><span style="color:#64748B;font-size:11px">Dienst</span><div style="color:#fff;font-size:14px;margin-top:2px">'+(SV[d.service]||d.service)+'</div></div>';
                html+='<div style="background:#1B2A4A;padding:12px;border-radius:8px"><span style="color:#64748B;font-size:11px">Status</span><div style="margin-top:4px">'+sb(d.status)+'</div></div>';
                html+='<div style="background:#1B2A4A;padding:12px;border-radius:8px"><span style="color:#64748B;font-size:11px">Gepubliceerd</span><div style="color:#fff;font-size:14px;margin-top:2px">'+(d.published_at||'-')+'</div></div></div>';
                const ci=WF.indexOf(d.status);
                if(ci>=0){html+='<div style="margin-bottom:16px"><div style="color:#94A3B8;font-size:12px;margin-bottom:8px">Workflow Status</div><div style="display:flex;gap:4px;align-items:center">';
                WF.forEach((s,idx)=>{html+='<div style="flex:1;text-align:center;padding:6px 0;border-radius:4px;font-size:11px;font-weight:600;'+(idx<=ci?'background:'+SC[s]+';color:#fff':'background:#1B2A4A;color:#475569')+'">'+SL[s]+'</div>';if(idx<WF.length-1)html+='<div style="color:'+(idx<ci?SC[s]:'#334155')+';font-size:14px">&#9654;</div>';});
                html+='</div></div>';}
                if(d.description)html+='<div style="margin-bottom:14px"><div style="color:#94A3B8;font-size:12px;margin-bottom:4px">Beschrijving</div><div style="color:#fff;font-size:13px;background:#1B2A4A;padding:12px;border-radius:8px">'+d.description+'</div></div>';
                if(d.content){let cs=d.content;try{cs=JSON.stringify(JSON.parse(d.content),null,2);}catch(e){}html+='<div style="margin-bottom:14px"><div style="color:#94A3B8;font-size:12px;margin-bottom:4px">Content</div><pre style="background:#0A1628;color:#E2E8F0;padding:12px;border-radius:8px;font-size:12px;overflow:auto;max-height:200px;white-space:pre-wrap">'+cs+'</pre></div>';}
                if(d.parameters){let ps=d.parameters;try{ps=JSON.stringify(JSON.parse(d.parameters),null,2);}catch(e){}html+='<div style="margin-bottom:14px"><div style="color:#94A3B8;font-size:12px;margin-bottom:4px">Parameters</div><pre style="background:#0A1628;color:#E2E8F0;padding:12px;border-radius:8px;font-size:12px;overflow:auto;max-height:150px;white-space:pre-wrap">'+ps+'</pre></div>';}
                if(h.length){html+='<div style="margin-bottom:14px"><div style="color:#94A3B8;font-size:12px;margin-bottom:8px">Approval History</div>';
                h.forEach(x=>{const ac=x.action.includes('approve')||x.action==='publish'?'approved':x.action.includes('reject')?'rejected':'in_review';html+='<div style="display:flex;gap:10px;padding:8px 0;border-bottom:1px solid #1B2A4A;font-size:12px"><span style="color:'+SC[ac]+'">'+x.action+'</span><span style="color:#94A3B8">'+x.reviewer+'</span><span style="color:#475569;margin-left:auto">'+x.created_at+'</span></div>';if(x.comment)html+='<div style="color:#64748B;font-size:12px;padding:0 0 8px;font-style:italic">"'+x.comment+'"</div>';});html+='</div>';}
                if(i.length){html+='<div style="margin-bottom:14px"><div style="color:#94A3B8;font-size:12px;margin-bottom:8px">Module Integrations</div>';
                i.forEach(x=>{html+='<div style="display:flex;gap:10px;padding:6px 0;font-size:12px;align-items:center"><span style="color:'+(x.status==='success'?'#10B981':'#EF4444')+'">&#9679;</span><span style="color:#fff">'+(x.action||x.target_module)+'</span><span style="color:#64748B;margin-left:auto">'+(x.target_table||'')+'</span></div>';});html+='</div>';}
                html+='<div style="margin-top:16px;display:flex;gap:8px">'+ab(d)+'</div>';
                document.getElementById('dContent').innerHTML=html;
                document.getElementById('detailModal').style.display='flex';
            });
        }
        function openNewForm(){document.getElementById('newModal').style.display='flex';}
        loadStats();loadData();
        </script>
        '''
        return _page(body, page_title='Deliverable Management', active='deliverables')
