/*_############################################################################
  _##
  _##  SNMP4J-Agent 3 - PropertyMOTreeBuilderTest.java
  _##
  _##  Copyright (C) 2005-2026  Frank Fock (SNMP4J.org)
  _##
  _##  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.
  _##
  _##########################################################################*/

package org.snmp4j.agent.io.prop;

import org.junit.Test;
import org.snmp4j.agent.io.prop.MIBTree.Node;
import org.snmp4j.agent.util.MarkdownMIBTreeFormatter;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.Variable;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

import static org.junit.Assert.*;

/**
 * Unit tests for {@link PropertyMOTreeBuilder} and {@link MarkdownMIBTreeFormatter}, driven by the
 * bundled {@code SampleAgentConfig.properties}.
 */
public class PropertyMOTreeBuilderTest {

    private static final String SAMPLE = "/org/snmp4j/agent/example/SampleAgentConfig.properties";

    private MIBTree buildSample() throws Exception {
        Properties props = new Properties();
        try (InputStream in = getClass().getResourceAsStream(SAMPLE)) {
            assertNotNull("sample config not found on classpath: " + SAMPLE, in);
            props.load(in);
        }
        return new PropertyMOTreeBuilder(props).build();
    }

    @Test
    public void buildsScalarsAndTables() throws Exception {
        MIBTree tree = buildSample();
        assertTrue("default context expected", tree.getContexts().contains(null));

        Node root = tree.getRoot(null);
        assertNotNull(root);

        // sysContact.0 scalar
        Node sysContact = find(root, new OID("1.3.6.1.2.1.1.4.0"));
        assertNotNull(sysContact);
        assertTrue(sysContact.isScalar());
        assertEquals("System Administrator", sysContact.getScalarValue().toString());

        // vacmSecurityToGroupEntry table (11 rows x 3 columns)
        Node vacm = find(root, new OID("1.3.6.1.6.3.16.1.2.1"));
        assertNotNull(vacm);
        assertTrue(vacm.isTable());
        assertEquals(3, vacm.getTable().getColumnCount());
        assertEquals(10, vacm.getTable().getRows().size());
        // first row, first column value is the group name
        assertEquals("minaccessgroup", vacm.getTable().getRows().get(0).getValues()[0].toString());
    }

    @Test
    public void preservesUnresolvedReferences() throws Exception {
        MIBTree tree = buildSample();
        // sysORTable (1.3.6.1.2.1.1.9.1) row 0 col 2 references {$1.3.6.1.2.1.1.3.0} (sysUpTime.0)
        Node sysOR = find(tree.getRoot(null), new OID("1.3.6.1.2.1.1.9.1"));
        assertNotNull(sysOR);
        assertTrue(sysOR.isTable());
        Variable ref = sysOR.getTable().getRows().get(0).getValues()[2];
        assertTrue("expected an UnresolvedReference, got " + ref, ref instanceof UnresolvedReference);
        assertEquals("1.3.6.1.2.1.1.3.0", ((UnresolvedReference) ref).getReference());
        assertEquals("{$1.3.6.1.2.1.1.3.0}", ref.toString());
    }

    @Test
    public void formatsMarkdown() throws Exception {
        String md = new MarkdownMIBTreeFormatter().format(buildSample());
        assertTrue(md.contains("# MIB Configuration Overview"));
        assertTrue(md.contains("Context-independent (default)"));
        assertTrue(md.contains("`1.3.6.1.2.1.1.4.0`"));
        assertTrue(md.contains("| # | Index |"));
        assertTrue(md.contains("{$1.3.6.1.2.1.1.3.0}"));
        // Write the rendered overview for manual inspection.
        Files.write(Paths.get("target", "SampleAgentConfig.md"), md.getBytes(StandardCharsets.UTF_8));
    }

    /** Navigates from {@code root} to the node at the given absolute OID, or {@code null}. */
    private static Node find(Node root, OID oid) {
        Node current = root;
        for (int arc : oid.getValue()) {
            Node next = null;
            for (Node child : current.getChildren()) {
                if (child.getSubID() == arc) {
                    next = child;
                    break;
                }
            }
            if (next == null) {
                return null;
            }
            current = next;
        }
        return current;
    }
}
