from pathlib import Path
import re

files = [
    Path('resources/views/admin/rentals/index.blade.php'),
    Path('resources/views/admin/rentals/show.blade.php'),
    Path('resources/views/admin/reports/index.blade.php'),
    Path('resources/views/admin/returns/create.blade.php'),
    Path('resources/views/admin/returns/index.blade.php'),
    Path('resources/views/admin/returns/show.blade.php'),
]

for p in files:
    if not p.exists():
        print(f'MISSING {p}')
        continue
    text = p.read_text(encoding='utf-8')
    if "@extends('admin.layouts.app')" in text:
        print(f'SKIP already extends: {p}')
        continue

    title_match = re.search(r'<title>(.*?)</title>', text, re.I | re.S)
    title = title_match.group(1).strip() if title_match else p.stem.replace('_', ' ').title()

    body_match = re.search(r'<body[^>]*>(.*?)</body>', text, re.I | re.S)
    if not body_match:
        print(f'ERROR missing body: {p}')
        continue

    body = body_match.group(1).strip()

    styles = re.findall(r'<style\b[^>]*>.*?</style>', text, re.I | re.S)
    scripts = re.findall(r'<script\b[^>]*>.*?</script>', text, re.I | re.S)

    body_no_scripts = re.sub(r'<script\b[^>]*>.*?</script>', '', body, flags=re.I | re.S).strip()
    content_lines = []
    if styles:
        content_lines.extend(styles)
        content_lines.append('')
    content_lines.append(body_no_scripts)
    content = '\n'.join(content_lines).strip() + '\n'

    push = ''
    if scripts:
        push = "@push('scripts')\n" + '\n'.join(scripts) + '\n@endpush\n'

    escaped_title = title.replace("'", "\\'")
    new_text = (
        "@extends('admin.layouts.app')\n\n"
        f"@section('page-title', '{escaped_title}')\n\n"
        "@section('content')\n"
        f"{content}"
        "@endsection\n\n"
        f"{push}"
    )

    p.write_text(new_text, encoding='utf-8')
    print(f'UPDATED {p}')
