#!/usr/bin/env python3
"""
Simple HTTP server that opens DXF/DWG files in Autodesk DWG TrueView
Run this script, then use search_drawings_local.html to click on drawings

Written by Douglas Millner of NERX Power Consultants LLC - Social, Website, and Blog - https://linktr.ee/nerxpower

DISCLAIMER: The software is free for distribution. The user assumes all risk.
"""

from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib.parse
import subprocess
import os
import json
import glob

def find_trueview():
    """Find the DWG TrueView executable by scanning all potential locations"""
    
    # Search patterns for different installation locations
    search_patterns = [
        r"C:\Program Files\Autodesk\DWG TrueView*\DWGTrueView.exe",
        r"C:\Program Files (x86)\Autodesk\DWG TrueView*\DWGTrueView.exe",
        r"C:\Program Files\Autodesk\DWG TrueView*\dwgviewr.exe",
        r"C:\Program Files (x86)\Autodesk\DWG TrueView*\dwgviewr.exe",
    ]
    
    # Try all search patterns
    for pattern in search_patterns:
        matches = glob.glob(pattern)
        if matches:
            # Return the first match found (usually the latest version)
            return matches[0]
    
    # If glob search fails, try explicit year-by-year search
    base_paths = [
        r"C:\Program Files\Autodesk",
        r"C:\Program Files (x86)\Autodesk"
    ]
    
    years = range(2020, 2027)  # Check versions from 2020 to 2026
    executables = ['DWGTrueView.exe', 'dwgviewr.exe']
    
    for base in base_paths:
        if os.path.exists(base):
            for year in sorted(years, reverse=True):  # Check newest first
                for exe in executables:
                    path = os.path.join(base, f"DWG TrueView {year}", exe)
                    if os.path.exists(path):
                        return path
    
    return None

class DrawingOpenerHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        """Handle GET requests"""
        if self.path == '/' or self.path == '/index.html':
            # Serve the HTML file
            try:
                html_path = os.path.join(os.path.dirname(__file__), 'search_drawings_local.html')
                with open(html_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                self.send_response(200)
                self.send_header('Content-type', 'text/html; charset=utf-8')
                self.end_headers()
                self.wfile.write(content.encode('utf-8'))
            except Exception as e:
                self.send_error(500, f"Error loading HTML: {str(e)}")
        
        elif self.path.startswith('/open?file='):
            # Extract file path from URL
            query = urllib.parse.urlparse(self.path).query
            params = urllib.parse.parse_qs(query)
            
            if 'file' in params:
                filepath = urllib.parse.unquote(params['file'][0])
                
                # Security check - ensure file is in the expected directory
                base_dir = r"c:\selkirk4\autocad print - DXF"
                
                # Normalize the filepath - convert forward slashes to backslashes for Windows
                filepath_normalized = filepath.replace('/', '\\')
                full_path = os.path.join(base_dir, filepath_normalized)
                
                print(f"Attempting to open: {filepath}")
                print(f"  Full path: {full_path}")
                print(f"  File exists: {os.path.exists(full_path)}")
                
                if not os.path.exists(full_path):
                    # Try to provide helpful error message
                    dir_path = os.path.dirname(full_path)
                    if os.path.exists(dir_path):
                        available_files = os.listdir(dir_path)
                        error_msg = f"File not found: {filepath}\nDirectory exists but file not found.\nAvailable files: {', '.join(available_files[:5])}"
                    else:
                        error_msg = f"File not found: {filepath}\nDirectory does not exist: {dir_path}"
                    
                    self.send_response(404)
                    self.send_header('Content-type', 'application/json')
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.end_headers()
                    self.wfile.write(json.dumps({'error': error_msg}).encode())
                    print(f"✗ File not found: {full_path}")
                    return
                
                # Find TrueView
                trueview_exe = find_trueview()
                if not trueview_exe:
                    self.send_error(500, "DWG TrueView not found. Please install it or update the path in open_drawing_server.py")
                    return
                
                # Open the file in TrueView
                try:
                    subprocess.Popen([trueview_exe, full_path])
                    
                    # Send success response
                    self.send_response(200)
                    self.send_header('Content-type', 'application/json')
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.end_headers()
                    
                    response = {
                        'status': 'success',
                        'message': f'Opening {filepath} in DWG TrueView',
                        'trueview': trueview_exe
                    }
                    self.wfile.write(json.dumps(response).encode())
                    
                    print(f"✓ Opened: {filepath}")
                    
                except Exception as e:
                    self.send_error(500, f"Error opening file: {str(e)}")
                    print(f"✗ Error opening {filepath}: {str(e)}")
            else:
                self.send_error(400, "Missing 'file' parameter")
        
        elif self.path == '/status':
            # Status check endpoint
            trueview_exe = find_trueview()
            
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            response = {
                'status': 'running',
                'trueview_found': trueview_exe is not None,
                'trueview_path': trueview_exe
            }
            self.wfile.write(json.dumps(response).encode())
        
        else:
            self.send_error(404, "Unknown endpoint")
    
    def log_message(self, format, *args):
        """Suppress default logging, we'll do our own"""
        pass

def run_server(port=8765):
    """Start the server"""
    server_address = ('127.0.0.1', port)
    httpd = HTTPServer(server_address, DrawingOpenerHandler)
    
    print("=" * 60)
    print("DWG TrueView Drawing Opener Server")
    print("=" * 60)
    print("Written by Douglas Millner of NERX Power Consultants LLC")
    print("Social, Website, and Blog - https://linktr.ee/nerxpower")
    print("DISCLAIMER: The software is free for distribution. The user assumes all risk.")
    print("=" * 60)
    print(f"Server running on http://127.0.0.1:{port}")
    print()
    
    # Search for TrueView with diagnostics
    print("Searching for DWG TrueView...")
    
    # Show what directories we're checking
    base_paths = [
        r"C:\Program Files\Autodesk",
        r"C:\Program Files (x86)\Autodesk"
    ]
    
    for base in base_paths:
        if os.path.exists(base):
            print(f"  Checking: {base}")
            try:
                subdirs = [d for d in os.listdir(base) if "DWG" in d.upper() or "TrueView" in d]
                if subdirs:
                    for subdir in subdirs:
                        print(f"    Found: {subdir}")
            except Exception as e:
                print(f"    Error listing: {e}")
        else:
            print(f"  Not found: {base}")
    
    print()
    trueview_exe = find_trueview()
    
    if trueview_exe:
        print(f"✓ DWG TrueView found: {trueview_exe}")
    else:
        print("✗ DWG TrueView NOT found!")
        print("\nTroubleshooting:")
        print("1. Make sure DWG TrueView is installed")
        print("2. Check if it's installed in a custom location")
        print("3. Look for DWGTrueView.exe or dwgviewr.exe in:")
        print("   C:\\Program Files\\Autodesk\\")
        print("   C:\\Program Files (x86)\\Autodesk\\")
    
    print()
    print("IMPORTANT: Open your web browser and go to:")
    print(f"  >>> http://127.0.0.1:{port} <<<")
    print()
    print("(Do NOT open the HTML file directly - use the URL above)")
    print("Press Ctrl+C to stop the server")
    print("=" * 60)
    print()
    
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n\nShutting down server...")
        httpd.shutdown()

if __name__ == '__main__':
    run_server()