#!/usr/bin/env python3
"""Extract and validate JavaScript from the generated HTML report."""
import re
import subprocess
import os
import tempfile

HTML_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "A股K线指标扫描报告.html")

with open(HTML_FILE, 'r', encoding='utf-8') as f:
    html = f.read()

# Find all <script> blocks (not external)
script_blocks = re.findall(r'<script>(.*?)</script>', html, re.DOTALL)
print(f"Found {len(script_blocks)} inline script blocks")

for i, block in enumerate(script_blocks):
    print(f"\nScript block {i+1}: {len(block)} chars, {block.count(chr(10))} lines")
    
    # Check for common syntax issues
    # 1. Check for literal newlines inside single-quoted strings
    # This is tricky - we need to find single-quoted strings that span multiple lines
    
    # Simple check: look for patterns like 'text\nmore text' where \n is a literal newline
    lines = block.split('\n')
    in_single_quote = False
    in_double_quote = False
    in_template = False
    in_comment = False
    issues = []
    
    for line_num, line in enumerate(lines, 1):
        i = 0
        while i < len(line):
            c = line[i]
            
            # Handle comments
            if not in_single_quote and not in_double_quote and not in_template:
                if c == '/' and i + 1 < len(line):
                    if line[i+1] == '/':
                        break  # Rest of line is comment
                    elif line[i+1] == '*':
                        in_comment = True
                        i += 2
                        continue
                if c == '*' and i + 1 < len(line) and line[i+1] == '/':
                    in_comment = False
                    i += 2
                    continue
            
            if in_comment:
                i += 1
                continue
            
            # Handle escape sequences
            if c == '\\' and (in_single_quote or in_double_quote or in_template):
                i += 2  # Skip the escaped character
                continue
            
            # Handle string delimiters
            if c == "'" and not in_double_quote and not in_template:
                in_single_quote = not in_single_quote
            elif c == '"' and not in_single_quote and not in_template:
                in_double_quote = not in_double_quote
            elif c == '`' and not in_single_quote and not in_double_quote:
                in_template = not in_template
            
            i += 1
        
        # At end of line, check if we're still inside a string
        if in_single_quote and not in_template:
            issues.append(f"  Line {line_num}: Unterminated single-quoted string at end of line")
        if in_double_quote and not in_template:
            issues.append(f"  Line {line_num}: Unterminated double-quoted string at end of line")
    
    if issues:
        print(f"  ISSUES FOUND:")
        for issue in issues[:20]:
            print(issue)
    else:
        print(f"  No obvious string termination issues found")
    
    # Also check for </script> inside strings
    if '</script>' in block:
        print(f"  WARNING: Found </script> inside script block!")

# Try to validate with Node.js if available
try:
    # Write the JS to a temp file
    js_content = script_blocks[0] if script_blocks else ""
    with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False, encoding='utf-8') as f:
        f.write(js_content)
        temp_path = f.name
    
    result = subprocess.run(['node', '--check', temp_path], capture_output=True, text=True, timeout=10)
    if result.returncode == 0:
        print("\n✅ Node.js syntax check: PASSED")
    else:
        print(f"\n❌ Node.js syntax check: FAILED")
        print(f"Error: {result.stderr[:500]}")
    
    os.unlink(temp_path)
except FileNotFoundError:
    print("\n(Node.js not available for syntax check)")
except Exception as e:
    print(f"\n(Node.js check error: {e})")
