import sys

file_path = 'core/templates/core/door_visits.html'
with open(file_path, 'r') as f:
    content = f.read()

# 1. Add style for the custom control
style_to_add = """
    #map-controls {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 5;
    }
    .map-control-btn {
        background-color: #fff;
        border: 2px solid #fff;
        border-radius: 3px;
        box-shadow: 0 2px 6px rgba(0,0,0,.3);
        cursor: pointer;
        margin-bottom: 22px;
        text-align: center;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #666;
    }
    .map-control-btn:hover {
        color: #333;
    }
"""

if '</style>' in content:
    content = content.replace('</style>', style_to_add + '\n</style>')

# 2. Add the map controls container in the modal body
map_div = '<div id="map" style="width: 100%; height: 100%; min-height: 500px;"></div>'
map_controls = """
                <div id="map" style="width: 100%; height: 100%; min-height: 500px; position: relative;">
                    <div id="map-controls">
                        <button id="center-user" class="map-control-btn" title="Center on My Location">
                            <i class="bi bi-geo-alt-fill"></i>
                        </button>
                    </div>
                </div>"""

content = content.replace(map_div, map_controls)

# 3. Update the JavaScript
old_vars = '    var map;\n    var markers = [];\n    var mapData = {{ map_data_json|safe }};'
new_vars = '    var map;\n    var markers = [];\n    var userLocationMarker;\n    var mapData = {{ map_data_json|safe }};'
content = content.replace(old_vars, new_vars)

geolocation_logic = """
    function showUserLocation(centerOnUser = false) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };

                if (userLocationMarker) {
                    userLocationMarker.setPosition(pos);
                } else {
                    userLocationMarker = new google.maps.Marker({
                        position: pos,
                        map: map,
                        title: 'Your Location',
                        icon: {
                            path: google.maps.SymbolPath.CIRCLE,
                            fillColor: '#4285F4',
                            fillOpacity: 1,
                            scale: 8,
                            strokeColor: 'white',
                            strokeWeight: 2
                        }
                    });
                }
                
                if (centerOnUser) {
                    map.setCenter(pos);
                    map.setZoom(15);
                }
            }, function(error) {
                console.warn("Geolocation failed: " + error.message);
            }, {
                enableHighAccuracy: true,
                timeout: 5000,
                maximumAge: 0
            });
        }
    }
"""

content = content.replace('    function initMap() {', geolocation_logic + '\n    function initMap() {')

# Add call to showUserLocation in initMap and setup button
init_map_end = '        if (markers.length > 0) {\n            map.fitBounds(bounds);\n        }\n    }'
new_init_map_end = """        if (markers.length > 0) {
            map.fitBounds(bounds);
        }
        
        // Initial attempt to show user location
        showUserLocation();
        
        // Setup control button
        var centerBtn = document.getElementById('center-user');
        if (centerBtn) {
            centerBtn.addEventListener('click', function() {
                showUserLocation(true);
            });
        }
    }"""
content = content.replace(init_map_end, new_init_map_end)

with open(file_path, 'w') as f:
    f.write(content)
