import os
import glob

directory = 'c:/Users/HP/PythonProjects/dohainstall/frontend/src'
files = glob.glob(directory + '/**/*.tsx', recursive=True)

import_stmt = 'import { API_BASE_URL, getAuthHeaders } from "@/lib/api";\n'

for file in files:
    if 'login\\page.tsx' in file or 'login/page.tsx' in file: 
        continue
    
    with open(file, 'r', encoding='utf-8') as f:
        content = f.read()
        
    original_content = content

    if 'http://localhost:8000/api/v1' in content:
        content = content.replace('"http://localhost:8000/api/v1', '`${API_BASE_URL}')
        content = content.replace("'http://localhost:8000/api/v1", '`${API_BASE_URL}')
        content = content.replace("`http://localhost:8000/api/v1", '`${API_BASE_URL}')

    # Replace headers dicts
    content = content.replace('{ headers: { "X-Company-ID": "1" } }', '{ headers: getAuthHeaders() }')

    headers_block_1 = """headers: {
                    "Content-Type": "application/json",
                    "X-Company-ID": "1"
                }"""
    content = content.replace(headers_block_1, 'headers: getAuthHeaders()')
    
    headers_block_2 = """headers: { 
                 "Content-Type": "application/json", 
                 "X-Company-ID": "1" 
              }"""
    content = content.replace(headers_block_2, 'headers: getAuthHeaders()')

    # Catch any inline ones
    content = content.replace('headers: { "Content-Type": "application/json", "X-Company-ID": "1" }', 'headers: getAuthHeaders()')

    if content != original_content and 'import { API_BASE_URL' not in content:
        # Find first import and insert before
        lines = content.split('\n')
        for i, line in enumerate(lines):
            if line.startswith('import '):
                lines.insert(i, import_stmt.strip())
                break
        content = '\n'.join(lines)

    if content != original_content:
        with open(file, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f'Updated {file}')
