using NUnit.Framework;
using NcProgramManager.Cnc;
using NcProgramManager.Cnc.Models;

namespace NcProgramManager.Tests.Unit
{
    [TestFixture]
    public class NcProgramValidatorTests
    {
        // ── Universal rules ───────────────────────────────────────────────────

        [Test]
        public void Validate_BlockTooLong_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            string longLine = "O1234\n" + new string('X', 81);
            var r = v.Validate("O1234", longLine);
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "80"), Is.True);
        }

        [Test]
        public void Validate_BlockExactly80_NoLengthError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            string line80 = new string('G', 80);
            var r = v.Validate("O1234", "O1234\n" + line80);
            // Should not have a block-length error (may still have other errors)
            Assert.That(HasErrorContaining(r, "Block length"), Is.False);
        }

        [Test]
        public void Validate_LowercaseLetter_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            var r = v.Validate("O1234", "O1234\ng00 X10");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "Lowercase"), Is.True);
        }

        [Test]
        public void Validate_NoLowercase_NoLowercaseError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            var r = v.Validate("O1234", "O1234\nG00 X10 Y20");
            Assert.That(HasErrorContaining(r, "Lowercase"), Is.False);
        }

        [Test]
        public void Validate_TabCharacter_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            var r = v.Validate("O1234", "O1234\nG00\tX10");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "Tab"), Is.True);
        }

        [Test]
        public void Validate_NestedParentheses_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            var r = v.Validate("O1234", "O1234\nG00 ((NESTED))");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "Nested"), Is.True);
        }

        [Test]
        public void Validate_SingleParenComment_NoNestedError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            var r = v.Validate("O1234", "O1234\nG00 (COMMENT) X10");
            Assert.That(HasErrorContaining(r, "Nested"), Is.False);
        }

        [Test]
        public void Validate_CommentExceeds32Chars_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            string longComment = "(" + new string('A', 33) + ")";
            var r = v.Validate("O1234", "O1234\n" + longComment);
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "Comment length"), Is.True);
        }

        [Test]
        public void Validate_CommentExactly32Chars_NoCommentLengthError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            string comment = "(" + new string('A', 32) + ")";
            var r = v.Validate("O1234", "O1234\n" + comment);
            Assert.That(HasErrorContaining(r, "Comment length"), Is.False);
        }

        // ── Fanuc rules ───────────────────────────────────────────────────────

        [Test]
        public void Validate_Fanuc_ValidNameAndContent_Succeeds()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            var r = v.Validate("O1234", "O1234\nG00 X10 Y20\nM30");
            Assert.That(r.Success, Is.True);
        }

        [Test]
        public void Validate_Fanuc_NameNotOFourDigits_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            var r = v.Validate("PROG", "O1234\nG00");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "O####"), Is.True);
        }

        [Test]
        public void Validate_Fanuc_NameO12345_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            // 5 digits — invalid for Fanuc
            var r = v.Validate("O12345", "O1234\nG00");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "O####"), Is.True);
        }

        [Test]
        public void Validate_Fanuc_FirstLineNotONumber_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            var r = v.Validate("O1234", "G00 X10\nM30");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "First line"), Is.True);
        }

        [TestCase(CncManufacturer.Fanuc)]
        [TestCase(CncManufacturer.Mitsubishi)]
        public void Validate_LeadingBlankLineBeforeONumber_NoFirstLineError(CncManufacturer mfg)
        {
            // ISS-018: FanucProgram.Standardize() prepends a leading '\n', so the
            // O#### header lands on line[1]. First-line check must scan past blanks.
            var v = new NcProgramValidator(mfg);
            var r = v.Validate("O1234", "\nO1234\nG00 X10 Y20\nM30");
            Assert.That(HasErrorContaining(r, "First line"), Is.False);
            Assert.That(r.Success, Is.True);
        }

        [TestCase(CncManufacturer.Fanuc,      "O1234",    "O1234\nG00 X10;")]
        [TestCase(CncManufacturer.Mitsubishi, "O1234",    "O1234\nG00 X10;")]
        [TestCase(CncManufacturer.Siemens,    "PROG.MPF", "G00 X10;")]
        [TestCase(CncManufacturer.Heidenhain, "PROG.H",   "L X+10;")]
        public void Validate_SemicolonForbidden_ReturnsError(CncManufacturer m, string name, string content)
        {
            var r = new NcProgramValidator(m).Validate(name, content);
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, ";"), Is.True);
        }

        [Test]
        public void Validate_Fanuc_BracketForbidden_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            var r = v.Validate("O1234", "O1234\nG00 [X10]");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "["), Is.True);
        }

        [Test]
        public void Validate_Fanuc_MacroHash_ReturnsWarningNotError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            var r = v.Validate("O1234", "O1234\n#100=10");
            // Warnings alone do not cause failure
            Assert.That(r.Success, Is.True);
            Assert.That(HasWarningContaining(r, "#"), Is.True);
        }

        [Test]
        public void Validate_Fanuc_NameFromPathStripped()
        {
            var v = new NcProgramValidator(CncManufacturer.Fanuc);
            // Full path — name part is O1234
            var r = v.Validate("//CNC_MEM/USER/PATH1/O1234", "O1234\nG00 X10");
            Assert.That(HasErrorContaining(r, "O####"), Is.False);
        }

        // ── Mitsubishi rules ──────────────────────────────────────────────────

        [Test]
        public void Validate_Mitsubishi_ValidNameAndContent_Succeeds()
        {
            var v = new NcProgramValidator(CncManufacturer.Mitsubishi);
            var r = v.Validate("O1234", "O1234\nG00 X10\nM30");
            Assert.That(r.Success, Is.True);
        }

        [Test]
        public void Validate_Mitsubishi_BadName_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Mitsubishi);
            var r = v.Validate("PROG", "O1234\nG00");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "O####"), Is.True);
        }

        // ── Mazak rules (full passthrough) ────────────────────────────────────

        [Test]
        public void Validate_Mazak_ValidOProgram_Succeeds()
        {
            var v = new NcProgramValidator(CncManufacturer.Mazak);
            var r = v.Validate("O1234", "O1234\nG00 X10");
            Assert.That(r.Success, Is.True);
            Assert.That(r.Errors, Is.Empty);
        }

        [Test]
        public void Validate_Mazak_EightDigitOName_Succeeds()
        {
            // 8-digit O number would fail Fanuc 4-digit rule; Mazak passes through.
            var v = new NcProgramValidator(CncManufacturer.Mazak);
            var r = v.Validate("O12345678", "O12345678\nG00 X10");
            Assert.That(r.Success, Is.True);
            Assert.That(r.Errors, Is.Empty);
        }

        [Test]
        public void Validate_Mazak_NoOHeaderLeadingPercent_Succeeds()
        {
            var v = new NcProgramValidator(CncManufacturer.Mazak);
            var r = v.Validate("O1234", "%\nG00 X10\nM30");
            Assert.That(r.Success, Is.True);
            Assert.That(r.Errors, Is.Empty);
        }

        [Test]
        public void Validate_Mazak_FanucForbiddenChars_Succeeds()
        {
            // ';', '[', ']', '#' would be rejected/warned for Fanuc; Mazak passes through.
            var v = new NcProgramValidator(CncManufacturer.Mazak);
            var r = v.Validate("O1234", "O1234\nG00 X10;\nG01 [X20] #100=5");
            Assert.That(r.Success, Is.True);
            Assert.That(r.Errors, Is.Empty);
        }

        [Test]
        public void Validate_Mazak_LowercaseContent_Succeeds()
        {
            var v = new NcProgramValidator(CncManufacturer.Mazak);
            var r = v.Validate("O1234", "g00 x10");
            Assert.That(r.Success, Is.True);
            Assert.That(r.Errors, Is.Empty);
        }

        [Test]
        public void Validate_Mazak_BlockOver80Chars_Succeeds()
        {
            var v = new NcProgramValidator(CncManufacturer.Mazak);
            string longLine = "O1234\n" + new string('X', 81);
            var r = v.Validate("O1234", longLine);
            Assert.That(r.Success, Is.True);
            Assert.That(r.Errors, Is.Empty);
        }

        [Test]
        public void Validate_Mazak_ArbitraryFilename_Succeeds()
        {
            // Non-O name; no name-pattern enforcement for Mazak.
            var v = new NcProgramValidator(CncManufacturer.Mazak);
            var r = v.Validate("MYPART.NC", "O1234\nG00 X10");
            Assert.That(r.Success, Is.True);
            Assert.That(r.Errors, Is.Empty);
        }

        [Test]
        public void Validate_Mazak_EmptyContent_Succeeds()
        {
            // Passthrough: validator itself passes empty; machine layer guards empty separately.
            var v = new NcProgramValidator(CncManufacturer.Mazak);
            var r = v.Validate("O1234", "");
            Assert.That(r.Success, Is.True);
            Assert.That(r.Errors, Is.Empty);
        }

        // ── Siemens rules ─────────────────────────────────────────────────────

        [Test]
        public void Validate_Siemens_ValidNameAndContent_Succeeds()
        {
            var v = new NcProgramValidator(CncManufacturer.Siemens);
            var r = v.Validate("PROG.MPF", "G00 X10 Y20\nM30");
            Assert.That(r.Success, Is.True);
        }

        [Test]
        public void Validate_Siemens_NameNoDotMpf_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Siemens);
            var r = v.Validate("PROG", "G00 X10");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, ".MPF"), Is.True);
        }

        [Test]
        public void Validate_Siemens_LowercaseMpf_ReturnsNameError()
        {
            var v = new NcProgramValidator(CncManufacturer.Siemens);
            var r = v.Validate("prog.mpf", "G00 X10");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, ".MPF"), Is.True);
        }

        [Test]
        public void Validate_Siemens_NoFirstLineRequired()
        {
            var v = new NcProgramValidator(CncManufacturer.Siemens);
            var r = v.Validate("PROG.MPF", "G00 X10\nM30");
            Assert.That(HasErrorContaining(r, "First line"), Is.False);
        }

        [Test]
        public void Validate_Siemens_LowercaseContent_NoLowercaseError()
        {
            // Dopo refactor: Siemens esente da check lowercase
            var v = new NcProgramValidator(CncManufacturer.Siemens);
            var r = v.Validate("PROG.MPF", "g00 x10 y20");
            Assert.That(HasErrorContaining(r, "Lowercase"), Is.False);
        }

        [Test]
        public void Validate_Siemens_TabInContent_NoTabError()
        {
            var v = new NcProgramValidator(CncManufacturer.Siemens);
            var r = v.Validate("PROG.MPF", "G00\tX10");
            Assert.That(HasErrorContaining(r, "Tab"), Is.False);
        }

        [Test]
        public void Validate_Siemens_LongBlock_NoBlockLengthError()
        {
            var v = new NcProgramValidator(CncManufacturer.Siemens);
            string longLine = new string('G', 120);
            var r = v.Validate("PROG.MPF", longLine);
            Assert.That(HasErrorContaining(r, "Block length"), Is.False);
        }

        // ── Heidenhain rules ──────────────────────────────────────────────────

        [Test]
        public void Validate_Heidenhain_ValidNameAndContent_Succeeds()
        {
            var v = new NcProgramValidator(CncManufacturer.Heidenhain);
            var r = v.Validate("PROG.H", "L X+10 Y+20 R0 FMAX\nL Z-5 F500");
            Assert.That(r.Success, Is.True);
        }

        [Test]
        public void Validate_Heidenhain_NameNoDotH_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Heidenhain);
            var r = v.Validate("PROG", "L X+10");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, ".H"), Is.True);
        }

        [Test]
        public void Validate_Heidenhain_PercentForbidden_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Heidenhain);
            var r = v.Validate("PROG.H", "L X+10 % COMMENT");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "%"), Is.True);
        }

        [Test]
        public void Validate_Heidenhain_NoFirstLineRequired()
        {
            var v = new NcProgramValidator(CncManufacturer.Heidenhain);
            var r = v.Validate("PROG.H", "L X+10\nM30");
            Assert.That(HasErrorContaining(r, "First line"), Is.False);
        }

        [Test]
        public void Validate_Heidenhain_LowercaseContent_NoLowercaseError()
        {
            var v = new NcProgramValidator(CncManufacturer.Heidenhain);
            var r = v.Validate("PROG.H", "l x+10 y+20");
            Assert.That(HasErrorContaining(r, "Lowercase"), Is.False);
        }

        [Test]
        public void Validate_Heidenhain_TabInContent_NoTabError()
        {
            var v = new NcProgramValidator(CncManufacturer.Heidenhain);
            var r = v.Validate("PROG.H", "L\tX+10");
            Assert.That(HasErrorContaining(r, "Tab"), Is.False);
        }

        [Test]
        public void Validate_Heidenhain_LongBlock_NoBlockLengthError()
        {
            var v = new NcProgramValidator(CncManufacturer.Heidenhain);
            string longLine = "L X+" + new string('1', 100);
            var r = v.Validate("PROG.H", longLine);
            Assert.That(HasErrorContaining(r, "Block length"), Is.False);
        }

        // ── Fagor rules ───────────────────────────────────────────────────────

        [Test]
        public void Validate_Fagor_ValidNameAndContent_Succeeds()
        {
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate("PROG1", "G00 X10 Y20\nM30");
            Assert.That(r.Success, Is.True);
        }

        [Test]
        public void Validate_Fagor_NameTooLong_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate(new string('A', 25), "G00 X10");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "24"), Is.True);
        }

        [Test]
        public void Validate_Fagor_NameContainsTilde_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate("MA\u00f1ANA", "G00 X10");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "\u00f1"), Is.True);
        }

        [Test]
        public void Validate_Fagor_NameWithSymbol_ReturnsError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate("PROG@1", "G00 X10");
            Assert.That(r.Success, Is.False);
        }

        [Test]
        public void Validate_Fagor_LongBlock_NoBlockLengthError()
        {
            // Fagor esentato da check block 80
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            string longLine = new string('G', 120);
            var r = v.Validate("PROG1", longLine);
            Assert.That(HasErrorContaining(r, "Block length"), Is.False);
            Assert.That(HasErrorContaining(r, "80"), Is.False);
        }

        [Test]
        public void Validate_Fagor_Lowercase_NoLowercaseError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate("PROG1", "g00 x10");
            Assert.That(HasErrorContaining(r, "Lowercase"), Is.False);
        }

        [Test]
        public void Validate_Fagor_Tab_NoTabError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate("PROG1", "G00\tX10");
            Assert.That(HasErrorContaining(r, "Tab"), Is.False);
        }

        [Test]
        public void Validate_Fagor_NestedParens_NoNestedError()
        {
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate("PROG1", "G00 ((NESTED))");
            Assert.That(HasErrorContaining(r, "Nested"), Is.False);
        }

        [Test]
        public void Validate_Fagor_NameWithNcExtension_Succeeds()
        {
            // Regression: default ProgramExtension `.nc` non deve essere rifiutato
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate("PROG1.nc", "G00 X10");
            Assert.That(r.Success, Is.True);
        }

        [Test]
        public void Validate_Fagor_NameWithCustomExtension_Succeeds()
        {
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate("PROG1.pim", "G00 X10");
            Assert.That(r.Success, Is.True);
        }

        [Test]
        public void Validate_Fagor_StemWithSymbol_ReturnsError()
        {
            // Symbol nello stem invariato come errore
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate("PROG@1.nc", "G00 X10");
            Assert.That(r.Success, Is.False);
        }

        [Test]
        public void Validate_Fagor_NameContainsTildeEscaped_ReturnsError()
        {
            // Test con escape unicode esplicito \u00f1 per evitare codepage issues
            var v = new NcProgramValidator(CncManufacturer.Fagor);
            var r = v.Validate("MA\u00f1ANA", "G00 X10");
            Assert.That(r.Success, Is.False);
            Assert.That(HasErrorContaining(r, "\u00f1"), Is.True);
        }

        // ── Helpers ───────────────────────────────────────────────────────────

        private static bool HasErrorContaining(ValidationResult r, string fragment)
        {
            foreach (var e in r.Errors)
                if (e.Severity == ValidationSeverity.Error && e.Message.Contains(fragment))
                    return true;
            return false;
        }

        private static bool HasWarningContaining(ValidationResult r, string fragment)
        {
            foreach (var e in r.Errors)
                if (e.Severity == ValidationSeverity.Warning && e.Message.Contains(fragment))
                    return true;
            return false;
        }
    }
}
