import tempfile
from pathlib import Path
from click.testing import CliRunner
from markitect.shared.cli import cli
from markitect.ast_cache import ASTCache

# Create test similar to failing test
temp_dir = tempfile.mkdtemp()
cache_dir = Path(temp_dir) / ".ast_cache"

# Create test file
test_file = Path(temp_dir) / "test.md"
test_file.write_text("# Test")

print(f"Temp dir: {temp_dir}")
print(f"Cache dir: {cache_dir}")
print(f"Test file: {test_file}")

# Create cache like test does
cache = ASTCache(cache_dir)
cache.cache_file(test_file)

# Check cache files exist
cache_files = list(cache_dir.glob("*.ast.json"))
print(f"Cache files created: {len(cache_files)}")
print(f"Cache files: {cache_files}")

# Now run CLI in temp dir context
runner = CliRunner()

# Test 1: In current working directory
print("\n=== Test 1: Current working directory ===")
result1 = runner.invoke(cli, ['cache-clean'])
print(f"Exit code: {result1.exit_code}")
print(f"Output: {repr(result1.output)}")

# Test 2: Change working directory
print(f"\n=== Test 2: Change to temp directory ===")
import os
original_cwd = os.getcwd()
os.chdir(temp_dir)

result2 = runner.invoke(cli, ['cache-clean'])
print(f"Exit code: {result2.exit_code}")
print(f"Output: {repr(result2.output)}")

# Check what remains
cache_files_after = list(cache_dir.glob("*.ast.json"))
print(f"Cache files after: {len(cache_files_after)}")

os.chdir(original_cwd)