#!/usr/bin/env python3
"""
Interactive Thesis Statement Builder

Guides students through building strong, arguable thesis statements.
Designed for high school essay writing.

Usage:
    python3 build_thesis.py
    python3 build_thesis.py --topic "Topic" --question "Question"
"""

import sys
import json


def build_thesis_interactive():
    """Guide user through thesis building process."""
    print("\n=== Thesis Statement Builder ===\n")
    print("Let's build a strong, arguable thesis statement!\n")
    
    # Step 1: Topic
    print("Step 1: What is your essay topic?")
    print("(Example: The American Revolution, The Constitution, Free market economics)")
    topic = input("Topic: ").strip()
    
    if not topic:
        print("Error: Topic required")
        sys.exit(1)
    
    # Step 2: Question
    print(f"\nStep 2: What question are you answering about {topic}?")
    print("(Example: Why did it happen? What caused it? Why does it matter?)")
    question = input("Question: ").strip()
    
    if not question:
        print("Error: Question required")
        sys.exit(1)
    
    # Step 3: Position
    print(f"\nStep 3: What's YOUR answer to: {question}")
    print("(This is your main claim - what you'll argue in the essay)")
    position = input("Your answer: ").strip()
    
    if not position:
        print("Error: Position required")
        sys.exit(1)
    
    # Step 4: Evidence Preview
    print("\nStep 4: What evidence supports your answer?")
    print("(List 2-3 main points/examples that prove your claim)")
    print("Enter each piece of evidence on a new line. Press Enter twice when done.")
    
    evidence = []
    while True:
        ev = input("Evidence: ").strip()
        if not ev:
            break
        evidence.append(ev)
        if len(evidence) >= 3:
            break
    
    if len(evidence) < 2:
        print("Warning: You need at least 2 pieces of evidence for a strong thesis")
    
    # Step 5: Build thesis statement
    print("\n=== Building Your Thesis ===\n")
    
    # Simple thesis
    simple_thesis = f"{position}"
    
    # Enhanced thesis with evidence preview
    if len(evidence) == 2:
        enhanced_thesis = f"{position}, as evidenced by {evidence[0]} and {evidence[1]}."
    elif len(evidence) >= 3:
        enhanced_thesis = f"{position}, as demonstrated by {evidence[0]}, {evidence[1]}, and {evidence[2]}."
    else:
        enhanced_thesis = f"{position}, as shown by {evidence[0]}." if evidence else simple_thesis
    
    # Output
    print("SIMPLE THESIS:")
    print(f"  {simple_thesis}\n")
    
    print("ENHANCED THESIS (with evidence preview):")
    print(f"  {enhanced_thesis}\n")
    
    # Evaluation
    print("=== Thesis Evaluation ===\n")
    
    checks = {
        'Specific': len(position.split()) > 5,
        'Arguable': '?' not in position and not position.lower().startswith('i think'),
        'Supported': len(evidence) >= 2,
        'Clear': True  # Assume true if they got this far
    }
    
    for criterion, passes in checks.items():
        status = "✓" if passes else "✗"
        print(f"{status} {criterion}")
    
    if not checks['Specific']:
        print("\n⚠️  Tip: Make your thesis more specific. Add details!")
    
    if not checks['Arguable']:
        print("\n⚠️  Tip: Remove 'I think' or questions. State your claim directly!")
    
    if not checks['Supported']:
        print("\n⚠️  Tip: Add more evidence. You need at least 2 strong examples!")
    
    # Output JSON for programmatic use
    output = {
        'topic': topic,
        'question': question,
        'position': position,
        'evidence': evidence,
        'simple_thesis': simple_thesis,
        'enhanced_thesis': enhanced_thesis,
        'evaluation': checks
    }
    
    print("\n=== JSON Output ===")
    print(json.dumps(output, indent=2))


def build_thesis_from_args(topic: str, question: str):
    """Build thesis from command-line arguments (for scripting)."""
    print(f"Topic: {topic}")
    print(f"Question: {question}")
    print("\nPlease provide your position and evidence interactively.")
    build_thesis_interactive()


def show_examples():
    """Show thesis examples."""
    examples = [
        {
            'topic': 'American Revolution',
            'weak': 'The American Revolution was an important event.',
            'strong': 'The American Revolution succeeded because colonists unified around shared economic grievances more than political philosophy, as evidenced by widespread merchant support and working-class participation in boycotts.',
            'why_strong': 'Specific, arguable, previews evidence'
        },
        {
            'topic': 'The Constitution',
            'weak': 'The Constitution is a good document.',
            'strong': 'The Constitution\'s system of checks and balances prevented tyranny more effectively than the Articles of Confederation by distributing power across three branches and requiring cooperation for major decisions.',
            'why_strong': 'Comparative, specific, shows causation'
        },
        {
            'topic': 'Free Market Economics',
            'weak': 'Free markets are better than government control.',
            'strong': 'Free market competition improves product quality and reduces prices more effectively than government regulation, as demonstrated by the computer industry\'s rapid innovation and declining costs since the 1980s.',
            'why_strong': 'Specific claim, real-world example, measurable outcomes'
        }
    ]
    
    print("\n=== Thesis Examples ===\n")
    
    for ex in examples:
        print(f"Topic: {ex['topic']}")
        print(f"\nWEAK: {ex['weak']}")
        print(f"STRONG: {ex['strong']}")
        print(f"Why it's strong: {ex['why_strong']}\n")
        print("-" * 60)


def main():
    if '--help' in sys.argv or '-h' in sys.argv:
        print("Thesis Statement Builder")
        print("\nUsage:")
        print("  python3 build_thesis.py                    # Interactive mode")
        print("  python3 build_thesis.py --examples         # Show examples")
        print("  python3 build_thesis.py --topic T --question Q  # Start with topic/question")
        sys.exit(0)
    
    if '--examples' in sys.argv:
        show_examples()
        sys.exit(0)
    
    # Check for topic and question args
    topic = None
    question = None
    
    if '--topic' in sys.argv:
        idx = sys.argv.index('--topic')
        if idx + 1 < len(sys.argv):
            topic = sys.argv[idx + 1]
    
    if '--question' in sys.argv:
        idx = sys.argv.index('--question')
        if idx + 1 < len(sys.argv):
            question = sys.argv[idx + 1]
    
    if topic and question:
        build_thesis_from_args(topic, question)
    else:
        build_thesis_interactive()


if __name__ == '__main__':
    main()
