#!/usr/bin/env python3
"""
OASIS HTML Document Fixer
Fixes common issues in OASIS specification HTML files:
1. Standardizes OASIS logo to use the official template URL
2. Creates symbolic links for missing image directories
3. Validates and reports any issues found

Usage: python fix_oasis_html.py [path_to_html_file_or_directory]
"""

import os
import sys
import re
import shutil
from pathlib import Path
from typing import List, Tuple, Optional
import logging

# OASIS Standard Logo URL - this should ALWAYS be used
OASIS_LOGO_URL = "https://docs.oasis-open.org/templates/OASISLogo-v3.0.png"

# Common patterns for OASIS logo references that need fixing
LOGO_PATTERNS = [
    r'src="[^"]*_files/image001\.png"',
    r'src="[^"]*images/image001\.png"', 
    r'src="[^"]*image001\.png"'
]

# Setup logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
logger = logging.getLogger(__name__)

class OASISHTMLFixer:
    def __init__(self, dry_run: bool = False):
        self.dry_run = dry_run
        self.fixes_made = 0
        self.files_processed = 0
        
    def fix_html_file(self, html_path: Path) -> bool:
        """Fix a single HTML file"""
        if not html_path.exists() or not html_path.suffix.lower() == '.html':
            logger.warning(f"Skipping non-HTML file: {html_path}")
            return False
            
        logger.info(f"Processing: {html_path}")
        self.files_processed += 1
        
        try:
            # Read the HTML content
            with open(html_path, 'r', encoding='utf-8', errors='ignore') as f:
                content = f.read()
            
            original_content = content
            
            # Fix OASIS logo references
            content = self._fix_logo_references(content, html_path)
            
            # Handle image directory issues
            self._handle_image_directories(html_path)
            
            # Write back if changes were made
            if content != original_content:
                if not self.dry_run:
                    with open(html_path, 'w', encoding='utf-8') as f:
                        f.write(content)
                    logger.info(f"✅ Fixed logo references in: {html_path}")
                else:
                    logger.info(f"🔍 Would fix logo references in: {html_path}")
                self.fixes_made += 1
                return True
            else:
                logger.info(f"✅ No fixes needed for: {html_path}")
                return False
                
        except Exception as e:
            logger.error(f"❌ Error processing {html_path}: {e}")
            return False
    
    def _fix_logo_references(self, content: str, html_path: Path) -> str:
        """Replace any OASIS logo reference with the standard URL"""
        fixes_in_file = 0
        
        for pattern in LOGO_PATTERNS:
            matches = re.findall(pattern, content)
            if matches:
                logger.info(f"  Found {len(matches)} logo reference(s) to fix")
                content = re.sub(pattern, f'src="{OASIS_LOGO_URL}"', content)
                fixes_in_file += len(matches)
        
        if fixes_in_file > 0:
            logger.info(f"  Standardized {fixes_in_file} logo reference(s)")
            
        return content
    
    def _handle_image_directories(self, html_path: Path) -> None:
        """Handle missing image directories by creating symbolic links"""
        html_dir = html_path.parent
        
        # Look for patterns like "filename_files/imageXXX" in the HTML
        with open(html_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        # Find all references to *_files/image* patterns
        files_dir_pattern = r'src="([^"]*_files)/([^"]*)"'
        matches = re.findall(files_dir_pattern, content)
        
        if matches:
            # Get the expected directory name (e.g., "document_files")
            expected_dirs = set(match[0] for match in matches)
            
            for expected_dir in expected_dirs:
                expected_path = html_dir / expected_dir
                images_path = html_dir / "images"
                
                if not expected_path.exists() and images_path.exists():
                    if not self.dry_run:
                        # Create the expected directory and link all images
                        expected_path.mkdir(exist_ok=True)
                        for img_file in images_path.iterdir():
                            if img_file.is_file():
                                link_path = expected_path / img_file.name
                                if not link_path.exists():
                                    link_path.symlink_to(f"../images/{img_file.name}")
                        logger.info(f"  Created image directory structure: {expected_dir}")
                    else:
                        logger.info(f"  Would create image directory structure: {expected_dir}")
    
    def process_directory(self, directory: Path) -> None:
        """Process all HTML files in a directory"""
        html_files = list(directory.rglob("*.html"))
        
        if not html_files:
            logger.warning(f"No HTML files found in: {directory}")
            return
            
        logger.info(f"Found {len(html_files)} HTML file(s) to process")
        
        for html_file in html_files:
            self.fix_html_file(html_file)
    
    def report_summary(self) -> None:
        """Report summary of fixes made"""
        logger.info(f"""
📊 OASIS HTML Fixer Summary:
  Files processed: {self.files_processed}
  Files fixed: {self.fixes_made}
  Mode: {'DRY RUN' if self.dry_run else 'LIVE'}
        """)

def main():
    import argparse
    
    parser = argparse.ArgumentParser(description="Fix common OASIS HTML specification issues")
    parser.add_argument("path", nargs="?", default=".", 
                       help="Path to HTML file or directory (default: current directory)")
    parser.add_argument("--dry-run", action="store_true", 
                       help="Show what would be fixed without making changes")
    parser.add_argument("--verbose", "-v", action="store_true", 
                       help="Verbose output")
    
    args = parser.parse_args()
    
    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)
    
    path = Path(args.path)
    
    if not path.exists():
        logger.error(f"Path does not exist: {path}")
        sys.exit(1)
    
    fixer = OASISHTMLFixer(dry_run=args.dry_run)
    
    if path.is_file():
        fixer.fix_html_file(path)
    else:
        fixer.process_directory(path)
    
    fixer.report_summary()

if __name__ == "__main__":
    main()
