#!/usr/bin/env python3
"""
Update coverage gutters configuration and fix coverage paths.
This script ensures Coverage Gutters can properly display coverage information.
"""

import os
import json


def main():
    """Main function to fix coverage gutters configuration."""

    print("=== Coverage Gutters Fix ===")
    print(f"Current working directory: {os.getcwd()}")

    # 1. Check if coverage.xml exists
    if os.path.exists('coverage.xml'):
        print("✓ coverage.xml exists")

        # Check file size and basic content
        size = os.path.getsize('coverage.xml')
        print(f"✓ coverage.xml size: {size} bytes")

        # Read first few lines to verify it's valid XML
        try:
            with open('coverage.xml', 'r') as f:
                first_line = f.readline().strip()
                if first_line.startswith('<?xml'):
                    print("✓ coverage.xml appears to be valid XML")
                else:
                    print("✗ coverage.xml does not start with XML declaration")
        except Exception as e:
            print(f"✗ Error reading coverage.xml: {e}")
    else:
        print("✗ coverage.xml does not exist")
        print("Running coverage to generate coverage.xml...")
        os.system("python -m coverage run --source=pyWebLayout -m unittest tests.test_abstract_inline")
        os.system("python -m coverage xml")

    # 2. Check VSCode settings
    vscode_settings_path = '.vscode/settings.json'
    if os.path.exists(vscode_settings_path):
        print("✓ VSCode settings.json exists")

        with open(vscode_settings_path, 'r') as f:
            try:
                settings = json.load(f)
                gutters_config = {k: v for k, v in settings.items() if 'coverage-gutters' in k}
                if gutters_config:
                    print("✓ Coverage Gutters settings found:")
                    for key, value in gutters_config.items():
                        print(f"  {key}: {value}")
                else:
                    print("✗ No Coverage Gutters settings found")
            except json.JSONDecodeError as e:
                print(f"✗ Error parsing VSCode settings: {e}")
    else:
        print("✗ VSCode settings.json not found")

    # 3. Check if inline.py file exists
    inline_file = 'pyWebLayout/abstract/inline.py'
    if os.path.exists(inline_file):
        print(f"✓ {inline_file} exists")

        # Check file size
        size = os.path.getsize(inline_file)
        print(f"✓ {inline_file} size: {size} bytes")
    else:
        print(f"✗ {inline_file} does not exist")

    # 4. Run a fresh coverage collection specifically for the inline module
    print("\n=== Running Fresh Coverage ===")
    try:
        print("Running tests with coverage...")
        os.system("python -m coverage erase")  # Clear old coverage data
        os.system("python -m coverage run --source=pyWebLayout -m unittest tests -v")
        os.system("python -m coverage xml -o coverage.xml")
        os.system("python -m coverage report --include='pyWebLayout/abstract/inline.py'")
        print("✓ Fresh coverage data generated")
    except Exception as e:
        print(f"✗ Error generating coverage: {e}")

    # 5. Instructions for manual verification
    print("\n=== Manual Verification Steps ===")
    print("1. In VSCode, open the Command Palette (Ctrl+Shift+P)")
    print("2. Run 'Coverage Gutters: Display Coverage'")
    print("3. If coverage doesn't appear, try:")
    print("   - 'Coverage Gutters: Remove Coverage'")
    print("   - 'Coverage Gutters: Display Coverage' again")
    print("4. Check that coverage.xml contains data for pyWebLayout/abstract/inline.py")
    print("5. The file should show 100% coverage (all lines covered)")

    print("\n=== Troubleshooting ===")
    print("If coverage still doesn't show:")
    print("1. Restart VSCode")
    print("2. Check Coverage Gutters extension is enabled")
    print("3. Try running: python run_coverage_gutters.py")
    print("4. Check VSCode Output panel for Coverage Gutters logs")


if __name__ == "__main__":
    main()
