#!/usr/bin/env python3
"""
Literature Validation Test Runner

This script runs wKrQ and ACrQ CLI commands from literature test cases
and captures their output for manual verification. Run with:

python examples/literature_validation.py > validation_output.txt

This generates a comprehensive test log that can be manually inspected
to verify the implementation against established literature.
"""

import subprocess
import sys
from typing import List, Tuple


def run_wkrq_command(args: List[str]) -> Tuple[str, str, int]:
    """Run a wkrq command and return stdout, stderr, and return code."""
    cmd = ["python", "-m", "wkrq"] + args
    try:
        result = subprocess.run(
            cmd, capture_output=True, text=True, timeout=30
        )
        return result.stdout, result.stderr, result.returncode
    except subprocess.TimeoutExpired:
        return "", "TIMEOUT", 1
    except Exception as e:
        return "", f"ERROR: {e}", 1


def print_test_section(title: str):
    """Print a formatted test section header."""
    print(f"\n{'='*80}")
    print(f" {title}")
    print('='*80)


def print_test_case(description: str, command: List[str]):
    """Print a test case with its command and output."""
    print(f"\n{'-'*60}")
    print(f"Test: {description}")
    print(f"Command: wkrq {' '.join(command)}")
    print(f"{'-'*60}")
    
    stdout, stderr, returncode = run_wkrq_command(command)
    
    if stderr and stderr != "":
        print(f"STDERR: {stderr}")
    
    if returncode != 0:
        print(f"RETURN CODE: {returncode}")
    
    print(stdout)


def main():
    """Run all literature validation tests."""
    
    print("wKrQ Literature Validation Test Suite")
    print("="*80)
    print("This output validates the implementation against literature test cases.")
    print("Each test shows the command run and its complete output including tableau trees.")
    print(f"Generated by: {__file__}")
    
    # wKrQ Tableau Rules Examples
    print_test_section("wKrQ Tableau Rules (All Rules Demonstrated)")
    
    # Alpha Rules (Non-branching)
    print_test_case(
        "T-Conjunction Rule: T:(A & B) produces T:A and T:B",
        ["--sign=T", "--tree", "--show-rules", "p & q"]
    )
    
    print_test_case(
        "F-Disjunction Rule: F:(A | B) produces F:A and F:B",
        ["--sign=F", "--tree", "--show-rules", "p | q"]
    )
    
    print_test_case(
        "T-Negation Rule: T:~A produces F:A",
        ["--sign=T", "--tree", "--show-rules", "~p"]
    )
    
    print_test_case(
        "F-Negation Rule: F:~A produces T:A",
        ["--sign=F", "--tree", "--show-rules", "~p"]
    )
    
    print_test_case(
        "N-Conjunction Rule: N:(A & B) produces N:A and N:B",
        ["--sign=N", "--tree", "--show-rules", "p & q"]
    )
    
    print_test_case(
        "N-Disjunction Rule: N:(A | B) produces N:A and N:B",
        ["--sign=N", "--tree", "--show-rules", "p | q"]
    )
    
    print_test_case(
        "N-Implication Rule: N:(A -> B) produces N:A and N:B",
        ["--sign=N", "--tree", "--show-rules", "p -> q"]
    )
    
    print_test_case(
        "N-Negation Rule: N:~A produces N:A",
        ["--sign=N", "--tree", "--show-rules", "~p"]
    )
    
    # Beta Rules (Branching)
    print_test_case(
        "T-Disjunction Rule: T:(A | B) branches to T:A or T:B",
        ["--sign=T", "--tree", "--show-rules", "p | q"]
    )
    
    print_test_case(
        "F-Conjunction Rule: F:(A & B) branches to F:A or F:B",
        ["--sign=F", "--tree", "--show-rules", "p & q"]
    )
    
    print_test_case(
        "T-Implication Rule: T:(A -> B) branches to F:A or T:B",
        ["--sign=T", "--tree", "--show-rules", "p -> q"]
    )
    
    print_test_case(
        "F-Implication Rule: F:(A -> B) produces T:A and F:B",
        ["--sign=F", "--tree", "--show-rules", "p -> q"]
    )
    
    print_test_case(
        "M-Propositional Rule: M:p branches to T:p or F:p",
        ["--sign=M", "--tree", "--show-rules", "p"]
    )
    
    print_test_case(
        "M-Compound Rule: M:(A & B) branches to M:A and M:B",
        ["--sign=M", "--tree", "--show-rules", "p & q"]
    )
    
    # Quantifier Rules
    print_test_case(
        "T-Universal Rule: T:[∀X P(X)]Q(X) branches to F:P(c) or T:Q(c)",
        ["--sign=T", "--tree", "--show-rules", "[forall X Human(X)]Mortal(X)"]
    )
    
    print_test_case(
        "T-Existential Rule: T:[∃X P(X)]Q(X) produces T:P(c) and T:Q(c)",
        ["--sign=T", "--tree", "--show-rules", "[exists X Student(X)]Smart(X)"]
    )
    
    print_test_case(
        "F-Universal Rule: F:[∀X P(X)]Q(X) produces T:P(c) and F:Q(c)",
        ["--sign=F", "--tree", "--show-rules", "[forall X Human(X)]Mortal(X)"]
    )
    
    print_test_case(
        "F-Existential Rule: F:[∃X P(X)]Q(X) branches to F:P(c) or F:Q(c)",
        ["--sign=F", "--tree", "--show-rules", "[exists X Student(X)]Smart(X)"]
    )
    
    # ACrQ Bilateral Predicate Rules
    print_test_section("ACrQ Bilateral Predicate Rules (Paraconsistent Extension)")
    
    print_test_case(
        "ACrQ T-Positive Predicate: T:R(a) produces T:R(a) (no R* interaction)",
        ["--mode=acrq", "--sign=T", "--tree", "--show-rules", "Human(alice)"]
    )
    
    print_test_case(
        "ACrQ T-Negative Predicate: T:R*(a) produces T:R*(a) (no R interaction)",
        ["--mode=acrq", "--syntax=bilateral", "--sign=T", "--tree", "--show-rules", "Human*(alice)"]
    )
    
    print_test_case(
        "ACrQ F-Positive Predicate: F:R(a) produces F:R(a)",
        ["--mode=acrq", "--sign=F", "--tree", "--show-rules", "Human(alice)"]
    )
    
    print_test_case(
        "ACrQ F-Negative Predicate: F:R*(a) produces F:R*(a)",
        ["--mode=acrq", "--syntax=bilateral", "--sign=F", "--tree", "--show-rules", "Human*(alice)"]
    )
    
    print_test_case(
        "ACrQ N-Predicate: N:R(a) produces F:R(a) and F:R*(a) (knowledge gap)",
        ["--mode=acrq", "--sign=N", "--tree", "--show-rules", "Human(alice)"]
    )
    
    print_test_case(
        "ACrQ M-Predicate: M:R(a) branches to T:R(a) or F:R(a)",
        ["--mode=acrq", "--sign=M", "--tree", "--show-rules", "Human(alice)"]
    )
    
    print_test_case(
        "ACrQ Transparent Negation: ~R(a) becomes R*(a)",
        ["--mode=acrq", "--syntax=transparent", "--sign=T", "--tree", "--show-rules", "~Human(alice)"]
    )
    
    print_test_case(
        "ACrQ Knowledge Glut: R(a) & R*(a) is satisfiable (paraconsistent)",
        ["--mode=acrq", "--syntax=transparent", "--sign=T", "--tree", "--show-rules", "Human(alice) & ~Human(alice)"]
    )
    
    print_test_case(
        "ACrQ Compound with Bilateral: (R(a) | S*(b)) & T(c)",
        ["--mode=acrq", "--syntax=mixed", "--sign=T", "--tree", "--show-rules", "(Human(alice) | Robot*(bob)) & Alien(charlie)"]
    )
    
    print_test_case(
        "ACrQ No Explosion: Contradiction doesn't entail arbitrary formula",
        ["--mode=acrq", "--inference", "--tree", "--show-rules", "Human(alice), ~Human(alice) |- Robot(bob)"]
    )
    
    # Unsatisfiable with Different Signs
    print_test_section("Unsatisfiable Cases with Different Signs")
    
    print_test_case(
        "Tautology cannot be false (F-sign unsatisfiable)",
        ["--sign=F", "--tree", "--show-rules", "p | ~p"]
    )
    
    print_test_case(
        "Contradiction cannot be true (T-sign unsatisfiable)",
        ["--sign=T", "--tree", "--show-rules", "p & ~p"]
    )
    
    print_test_case(
        "Double negation elimination failure",
        ["--sign=F", "--tree", "--show-rules", "p -> ~~p"]
    )
    
    print_test_case(
        "Law of excluded middle cannot be false",
        ["--sign=F", "--tree", "--show-rules", "(p -> q) | (p -> ~q)"]
    )
    
    print_test_case(
        "Pierce's law cannot be undefined",
        ["--sign=N", "--tree", "--show-rules", "((p -> q) -> p) -> p"]
    )

    # Epistemic vs Truth-Functional
    print_test_section("Epistemic vs Truth-Functional Distinction")
    
    print_test_case(
        "Truth-functional contradiction (unsatisfiable)",
        ["--sign=T", "--tree", "--show-rules", "p & ~p"]
    )
    
    print_test_case(
        "Epistemic uncertainty about contradiction (satisfiable)",
        ["--sign=M", "--tree", "--show-rules", "p & ~p"]
    )
    
    print_test_case(
        "Contradiction can be undefined (satisfiable)",
        ["--sign=N", "--tree", "--show-rules", "p & ~p"]
    )

    # Smullyan Alpha Rules (Non-branching)
    print_test_section("Smullyan Alpha Rules (Non-branching)")
    
    print_test_case(
        "T-Conjunction (alpha rule)",
        ["--sign=T", "--tree", "--show-rules", "p & q"]
    )
    
    print_test_case(
        "F-Disjunction (alpha rule)",
        ["--sign=F", "--tree", "--show-rules", "p | q"]
    )
    
    print_test_case(
        "T-Negation (alpha rule)",
        ["--sign=T", "--tree", "--show-rules", "~p"]
    )

    # Smullyan Beta Rules (Branching)
    print_test_section("Smullyan Beta Rules (Branching)")
    
    print_test_case(
        "T-Disjunction (beta rule - should branch)",
        ["--sign=T", "--tree", "--show-rules", "p | q"]
    )
    
    print_test_case(
        "F-Conjunction (beta rule - should branch)",
        ["--sign=F", "--tree", "--show-rules", "p & q"]
    )
    
    print_test_case(
        "T-Implication (beta rule - should branch)",
        ["--sign=T", "--tree", "--show-rules", "p -> q"]
    )

    # Classical Valid Inferences
    print_test_section("Classical Valid Inferences")
    
    print_test_case(
        "Modus Ponens",
        ["--inference", "--tree", "--show-rules", "p, p -> q |- q"]
    )
    
    print_test_case(
        "Modus Tollens",
        ["--inference", "--tree", "--show-rules", "p -> q, ~q |- ~p"]
    )
    
    print_test_case(
        "Hypothetical Syllogism",
        ["--inference", "--tree", "--show-rules", "p -> q, q -> r |- p -> r"]
    )
    
    print_test_case(
        "Disjunctive Syllogism",
        ["--inference", "--tree", "--show-rules", "p | q, ~p |- q"]
    )

    # Classical Invalid Inferences
    print_test_section("Classical Invalid Inferences (Should Show Countermodels)")
    
    print_test_case(
        "Affirming the Consequent (invalid)",
        ["--inference", "--countermodel", "--show-rules", "p -> q, q |- p"]
    )
    
    print_test_case(
        "Denying the Antecedent (invalid)",
        ["--inference", "--countermodel", "--show-rules", "p -> q, ~p |- ~q"]
    )
    
    # Additional Valid Inferences (More Closed Branches)
    print_test_section("Additional Valid Inferences (Complex Closed Branch Patterns)")
    
    print_test_case(
        "Contradiction in premises",
        ["--inference", "--tree", "--show-rules", "p, ~p |- q"]
    )
    
    print_test_case(
        "Complex tautology inference",
        ["--inference", "--tree", "--show-rules", "p -> q, q -> r, r -> s |- p -> s"]
    )
    
    print_test_case(
        "Disjunction elimination",
        ["--inference", "--tree", "--show-rules", "p | q, p -> r, q -> r |- r"]
    )
    
    print_test_case(
        "Proof by cases",
        ["--inference", "--tree", "--show-rules", "p | ~p, p -> q, ~p -> q |- q"]
    )
    
    print_test_case(
        "Constructive dilemma",
        ["--inference", "--tree", "--show-rules", "(p -> q) & (r -> s), p | r |- q | s"]
    )
    
    print_test_case(
        "Quantifier inference with closure",
        ["--inference", "--tree", "--show-rules", "[forall X Human(X)]Mortal(X), [forall Y Mortal(Y)]Dies(Y), Human(socrates) |- Dies(socrates)"]
    )

    # First-Order Logic with Restricted Quantifiers
    print_test_section("First-Order Logic with Restricted Quantifiers")
    
    print_test_case(
        "Universal quantifier with ASCII syntax",
        ["--tree", "--show-rules", "[forall X Human(X)]Mortal(X)"]
    )
    
    print_test_case(
        "Existential quantifier with ASCII syntax",
        ["--tree", "--show-rules", "[exists X Student(X)]Human(X)"]
    )
    
    print_test_case(
        "Valid universal inference",
        ["--inference", "--tree", "--show-rules", "[forall X Human(X)]Mortal(X), Human(socrates) |- Mortal(socrates)"]
    )

    # Complex First-Order Examples
    print_test_section("Complex First-Order Examples")
    
    print_test_case(
        "Multiple quantifiers",
        ["--tree", "--show-rules", "[forall X Human(X)]Mortal(X) & [exists Y Student(Y)]Smart(Y)"]
    )
    
    print_test_case(
        "Medical inference with complex parsing",
        ["--inference", "--tree", "--show-rules", "[forall X [exists Y (beneficial(X,Y) & has_condition(Y,X))]]prescribed(X), beneficial(aspirin,patient_smith) & has_condition(patient_smith,aspirin) |- prescribed(aspirin)"]
    )

    # ACrQ Paraconsistent Examples
    print_test_section("ACrQ Paraconsistent Examples")
    
    print_test_case(
        "Basic bilateral predicate (transparent mode)",
        ["--mode=acrq", "--tree", "--show-rules", "Human(alice)"]
    )
    
    print_test_case(
        "Explicit bilateral syntax",
        ["--mode=acrq", "--syntax=bilateral", "--tree", "--show-rules", "Human*(alice)"]
    )
    
    print_test_case(
        "Knowledge gap (N-sign)",
        ["--mode=acrq", "--sign=N", "--tree", "--show-rules", "Human(alice)"]
    )
    
    print_test_case(
        "Knowledge glut (paraconsistent contradiction)",
        ["--mode=acrq", "--tree", "--show-rules", "Human(alice) & ~Human(alice)"]
    )
    
    print_test_case(
        "No explosion from contradiction",
        ["--mode=acrq", "--inference", "--countermodel", "--show-rules", "Human(alice) & ~Human(alice) |- Robot(bob)"]
    )

    # ACrQ Syntax Modes
    print_test_section("ACrQ Syntax Modes")
    
    print_test_case(
        "Transparent mode (automatic conversion)",
        ["--mode=acrq", "--syntax=transparent", "--tree", "--show-rules", "Human(alice) & ~Robot(bob)"]
    )
    
    print_test_case(
        "Mixed mode (both syntaxes)",
        ["--mode=acrq", "--syntax=mixed", "--tree", "--show-rules", "Human(alice) & Robot*(bob)"]
    )

    # Performance and Optimization Tests
    print_test_section("Performance and Optimization Validation")
    
    print_test_case(
        "Alpha rule prioritization (should be fast)",
        ["--tree", "--show-rules", "~(p & q) & (r | s)"]
    )
    
    print_test_case(
        "Complex formula (branch selection test)",
        ["--tree", "--show-rules", "(p | q) & (q | r) & (r | s) & (s | t)"]
    )
    
    print_test_case(
        "Early termination test",
        ["--tree", "--show-rules", "p | q | r | s | t"]
    )

    # Additional Unsatisfiable Cases
    print_test_section("Additional Unsatisfiable Cases (Closed Branch Demonstrations)")
    
    print_test_case(
        "Simple contradiction (p and not p)",
        ["--sign=T", "--tree", "--show-rules", "p & ~p"]
    )
    
    print_test_case(
        "Contradiction with disjunction",
        ["--sign=T", "--tree", "--show-rules", "(p | q) & ~p & ~q"]
    )
    
    print_test_case(
        "De Morgan's law contradiction",
        ["--sign=T", "--tree", "--show-rules", "~(p & q) & p & q"]
    )
    
    print_test_case(
        "Implication contradiction",
        ["--sign=T", "--tree", "--show-rules", "(p -> q) & p & ~q"]
    )
    
    print_test_case(
        "Multiple variable contradiction",
        ["--sign=T", "--tree", "--show-rules", "p & q & r & ~(p | q | r)"]
    )
    
    print_test_case(
        "Nested contradiction",
        ["--sign=T", "--tree", "--show-rules", "((p -> q) & (q -> r)) & p & ~r & q"]
    )
    
    print_test_case(
        "Cannot be both true and false",
        ["--sign=T", "--tree", "--show-rules", "(p -> q) & (~p -> q) & (p -> ~q) & (~p -> ~q)"]
    )
    
    print_test_case(
        "Quantifier contradiction",
        ["--sign=T", "--tree", "--show-rules", "[forall X P(X)]Q(X) & P(a) & ~Q(a)"]
    )
    
    print_test_case(
        "Mixed quantifier contradiction",
        ["--sign=T", "--tree", "--show-rules", "[forall X P(X)]Q(X) & [exists Y P(Y)]~Q(Y)"]
    )
    
    print_test_case(
        "Complex propositional unsatisfiable",
        ["--sign=T", "--tree", "--show-rules", "((p | q) -> r) & ((~p | ~q) -> r) & p & q & ~r"]
    )

    # Edge Cases and Error Conditions
    print_test_section("Edge Cases and Error Handling")
    
    print_test_case(
        "Invalid syntax (should show error)",
        ["--tree", "--show-rules", "p &"]
    )
    
    print_test_case(
        "Mixed quantifier syntax",
        ["--tree", "--show-rules", "[∀X Human(X)]Mortal(X) & [exists Y Student(Y)]Smart(Y)"]
    )

    print("\n" + "="*80)
    print("END OF VALIDATION TESTS")
    print("="*80)
    print("Review the output above to verify:")
    print("1. Tableau trees show correct rule application order")
    print("2. Alpha rules processed before beta rules")
    print("3. Valid inferences are recognized as valid")
    print("4. Invalid inferences show countermodels")
    print("5. ACrQ contradictions are satisfiable (paraconsistent)")
    print("6. Performance is reasonable (fast response times)")
    print("7. Error handling works for invalid syntax")


if __name__ == "__main__":
    main()