#!/usr/bin/env python3
"""
Fragment Generator for Thymeleaf Templates

Generates reusable Thymeleaf fragments for common patterns.
Usage: python fragment_generator.py <type> [options]
"""

import sys
import os
from pathlib import Path

class FragmentGenerator:
    def __init__(self):
        self.templates = {
            'form': self.generate_form_fragment,
            'table': self.generate_table_fragment,
            'card': self.generate_card_fragment,
            'modal': self.generate_modal_fragment,
            'navigation': self.generate_navigation_fragment
        }
    
    def generate_form_fragment(self, options):
        """Generate form fragment"""
        field_name = options.get('field', 'fieldName')
        field_type = options.get('type', 'text')
        required = options.get('required', False)
        
        required_attr = 'required' if required else ''
        required_class = 'required' if required else ''
        
        return f'''<!-- Form Field Fragment -->
<div th:fragment="formField(field, type, required)" class="mb-3">
  <label th:for="${{field}}" th:text="#{{form.${{field}}}}" class="form-label">Label</label>
  <input th:field="*{{${{field}}}}" 
         th:type="${{type ?: 'text'}}" 
         th:class="${{required ? 'form-control is-invalid' : 'form-control'}} {required_class}"
         class="form-control" />
  <div th:if="${{#fields.hasErrors({{field}})}}" class="invalid-feedback">
    <span th:each="error : ${{#fields.errors({{field}})}}" th:text="${{error}}"></span>
  </div>
</div>'''
    
    def generate_table_fragment(self, options):
        """Generate table fragment"""
        return '''<!-- Data Table Fragment -->
<table th:fragment="dataTable(items, columns, actions)" class="table table-striped table-hover">
  <thead class="table-dark">
    <tr>
      <th th:each="column : ${{columns}}" th:text="${{table.${{column}}}}">Column</th>
      <th th:if="${{actions}}" th:text="#{table.actions}">Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="item,stat : ${{items}}">
      <td th:each="column : ${{columns}}">
        <span th:text="${{item[column]}}">Data</span>
      </td>
      <td th:if="${{actions}}">
        <div class="btn-group" role="group">
          <a th:each="action : ${{actions}}"
             th:href="${{action.url.replace('{id}', item.id)}}"
             th:class="${{action.class}}"
             th:text="${{action.label}}">Action</a>
        </div>
      </td>
    </tr>
  </tbody>
</table>'''
    
    def generate_card_fragment(self, options):
        """Generate card fragment"""
        return '''<!-- Card Component Fragment -->
<div th:fragment="card(title, content, actions)" class="card mb-3">
  <div class="card-header d-flex justify-content-between align-items-center">
    <h5 class="card-title mb-0" th:text="${{title}}">Card Title</h5>
    <div th:if="${{actions}}" class="dropdown">
      <button class="btn btn-sm btn-outline-secondary dropdown-toggle" 
              type="button" data-bs-toggle="dropdown">
        <i class="fas fa-ellipsis-v"></i>
      </button>
      <ul class="dropdown-menu dropdown-menu-end">
        <li th:each="action : ${{actions}}">
          <a class="dropdown-item" 
             th:href="${{action.url}}" 
             th:text="${{action.label}}">Action</a>
        </li>
      </ul>
    </div>
  </div>
  <div class="card-body" th:utext="${{content}}">Card content</div>
</div>'''
    
    def generate_modal_fragment(self, options):
        """Generate modal fragment"""
        return '''<!-- Modal Fragment -->
<div th:fragment="confirmModal(id, title, message, action)" 
     class="modal fade" 
     th:id="'confirmModal-' + ${{id}}"
     tabindex="-1" 
     aria-labelledby="'confirmModalLabel-' + ${{id}}"
     aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" 
              th:id="'confirmModalLabel-' + ${{id}}"
              th:text="${{title}}">Confirm Action</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p th:text="${{message}}">Are you sure?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" 
                th:text="#{action.cancel}">Cancel</button>
        <form th:action="${{action}}" method="post" style="display: inline;">
          <input type="hidden" th:name="${{_csrf.parameterName}}" 
                 th:value="${{_csrf.token}}" />
          <button type="submit" class="btn btn-danger" th:text="#{action.confirm}">Confirm</button>
        </form>
      </div>
    </div>
  </div>
</div>'''
    
    def generate_navigation_fragment(self, options):
        """Generate navigation fragment"""
        return '''<!-- Navigation Fragment -->
<nav th:fragment="mainNav" class="navbar navbar-expand-lg navbar-dark bg-dark">
  <div class="container-fluid">
    <!-- Brand -->
    <a class="navbar-brand" th:href="@{/}" th:text="#{app.name}">App</a>
    
    <!-- Mobile toggle -->
    <button class="navbar-toggler" type="button" 
            data-bs-toggle="collapse" 
            data-bs-target="#navbarNav">
      <span class="navbar-toggler-icon"></span>
    </button>
    
    <!-- Navigation items -->
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav me-auto">
        <li class="nav-item">
          <a class="nav-link" th:href="@{/}" th:text="#{nav.home}">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" th:href="@{/users}" th:text="#{nav.users}">Users</a>
        </li>
      </ul>
      
      <!-- User menu -->
      <ul class="navbar-nav">
        <li class="nav-item dropdown" sec:authorize="isAuthenticated()">
          <a class="nav-link dropdown-toggle" href="#" 
             role="button" data-bs-toggle="dropdown">
            <i class="fas fa-user"></i>
            <span th:text="${{#authentication.name}}">User</span>
          </a>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" th:href="@{/profile}" th:text="#{nav.profile}">Profile</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item" th:href="@{/logout}" th:text="#{nav.logout}">Logout</a></li>
          </ul>
        </li>
        <li class="nav-item" sec:authorize="!isAuthenticated()">
          <a class="nav-link" th:href="@{/login}" th:text="#{nav.login}">Login</a>
        </li>
      </ul>
    </div>
  </div>
</nav>'''
    
    def generate(self, fragment_type, options=None):
        """Generate fragment of specified type"""
        if options is None:
            options = {}
        
        if fragment_type not in self.templates:
            print("Available fragment types:")
            for key in self.templates.keys():
                print("  {}".format(key))
            print()
            print("Usage: python fragment_generator.py <type> [options]")
            print("Example: python fragment_generator.py form --field=email --type=email --required=true")
            return 1
        
        fragment_content = self.templates[fragment_type](options)
        
        # Save to file
        filename = "fragments/{}_fragment.html".format(fragment_type)
        Path(filename).parent.mkdir(exist_ok=True)
        Path(filename).write_text(fragment_content, encoding='utf-8')
        
        print("Generated fragment: {}".format(filename))
        return 0

def main():
    if len(sys.argv) < 2:
        generator = FragmentGenerator()
        return generator.generate('help')
    
    fragment_type = sys.argv[1]
    options = {}
    
    # Parse command line options
    for arg in sys.argv[2:]:
        if arg.startswith('--'):
            key_value = arg[2:].split('=', 1)
            if len(key_value) == 2:
                options[key_value[0]] = key_value[1]
            else:
                options[key_value[0]] = True
    
    generator = FragmentGenerator()
    return generator.generate(fragment_type, options)

if __name__ == "__main__":
    sys.exit(main())