<prompt>
  <role>
    You are a developer tasked with building Magic Video from scratch,
    a local web app for Linux that makes FFmpeg easier to use.
    Implement and verify the app; do not stop at proposing a plan.
  </role>

  <objective>
    Build a complete app to resize, compress, crop, trim and convert video,
    as well as extract and optimise audio. The app must run locally,
    without accounts, databases or cloud services.
  </objective>

  <technologies>
    <backend>PHP 8.1 or later, FFmpeg and FFprobe.</backend>
    <frontend>Bootstrap 5, jQuery, HTML and CSS.</frontend>
    <dependencies>
      Include Bootstrap and jQuery in the project: no CDN dependencies
      and no Internet connection required during use. Keep their licences.
    </dependencies>
  </technologies>

  <installation>
    <destination>
      Use the existing default Apache virtual host, in a subfolder named
      exactly "Magic Video". Do not create a new virtual host.
    </destination>
    <checks>
      Identify the default HTTP virtual host and verify its effective
      DocumentRoot before installing. Do not assume it is /var/www/html.
      Stop the installation with an explanation if you cannot determine it.
    </checks>
    <privileges>
      Do not ask for passwords in chat. If privileges are needed, use an
      interactive terminal so the user can enter them there.
      If sudo is blocked by the environment, say so immediately, complete
      the project in the accessible workspace, and provide one manual
      command to install it on the actual computer.
    </privileges>
    <scripts>
      Provide install.sh for the first installation and an update script
      with backup and recovery in case of an error.
      Do not silently overwrite an existing installation.
      Do not install packages automatically.
    </scripts>
    <permissions>
      Apache must be able to read the code, but the web process must not be
      able to modify it. Working folders must be writable by the effective
      Apache user, normally www-data. Results must be readable by the local
      user in the file manager. Do not use permissions 777.
    </permissions>
  </installation>

  <features>
    <source>
      Select one file at a time using a file picker or drag and drop.
      Show its name, size, resolution and duration when available.
      Keep the original unchanged.
    </source>

    <presets>
      Use a dropdown with:
      - Web balanced: a compromise between quality and file size.
      - Smallest file: stronger compression and less detail.
      - Best quality: higher quality and potentially a larger file.
      For H.264, use CRF 23, 29 and 18 respectively, with the FFmpeg
      medium preset.
    </presets>

    <resizing>
      Offer maximum widths of 1920, 1280 and 854 pixels, or original
      resolution. Preserve aspect ratio, do not upscale, and ensure the
      dimensions are compatible with the selected codec.
    </resizing>

    <formats>
      <format>MP4: H.264, AAC, yuv420p pixel format and faststart.</format>
      <format>MKV: H.264 and AAC.</format>
      <format>WebM: VP9 and Opus.</format>
      <format>MP3 audio only.</format>
      <format>M4A audio only, with AAC and faststart.</format>
      <format>WAV audio only, PCM.</format>
      Disable video-only controls when an audio-only format is selected.
    </formats>

    <advanced_options>
      Organise them in a tabbed dialog:
      - Duration: start and duration in seconds, including decimals.
      - Crop: width, height, X and Y position in original pixels.
      - Audio: optional normalisation to -16 LUFS.
      - MB limit: optional maximum video file size.

      Validate values on the server. Crop before resizing.
      Prevent crops outside the source and trims beyond its duration.

      The MB limit must warn about possible quality loss. Use a bitrate
      strategy appropriate to the duration and measure the final result.
      If it exceeds the requested maximum, report the problem and discard
      only that job's result. Do not promise an exact file size.
    </advanced_options>

    <output>
      <folder>
        Allow the user to enter the absolute path of an existing folder.
        A "Check" button must actually create a temporary file, write to it
        and remove it. Repeat the check before conversion. Under Apache,
        run the check as the effective web-process user.
      </folder>
      <filename>
        Suggest a name based on the source file and preset:
        name-web, name-compressed or name-quality. Allow editing the name.
        After a manual edit, do not replace it when the preset changes.
        Show the extension separately and update it automatically for the
        selected format. Avoid duplicate extensions.
      </filename>
      <protection>
        Validate the name on the server too: no paths, separators, control
        characters or names too long for the filesystem. Support valid
        Italian and Unicode names. Never overwrite existing files: reserve
        the destination atomically and handle concurrent requests using the
        same name. An error must never delete a pre-existing file.
      </protection>
    </output>
  </features>

  <interface>
    <style>
      Professional, compact, ergonomic and colourful GUI. Use a dark
      blue-grey background, turquoise for the source, violet for settings
      and amber for the destination. Avoid oversized slogans, playful
      decoration and wasted space. Keep text readable, provide adequate
      contrast and support keyboard navigation.
    </style>
    <layout>
      Use a short header with the app name, History and System.
      On desktop, arrange three columns side by side:
      1. Source and preview.
      2. Preset dropdown, width and format.
      3. Filename, output folder, check and start controls.

      Reduce the video preview to about 100–122 pixels high, preserving its
      aspect ratio and playback controls. Show the progress bar below all
      three columns.

      At normal zoom, verify that the main controls, loaded preview and
      progress fit without scrolling in a 1280x640 desktop viewport. Do not
      achieve this by clipping content with overflow hidden or making text
      unreadable.

      Open History, diagnostics and advanced options in dedicated dialogs
      so they do not make the main screen taller. Allow the scrolling needed
      on small screens and at high zoom.
    </layout>
    <preview>
      State clearly that the preview plays the original file and does not
      simulate the result of compression or cropping. Connect every
      operational control to the backend.
    </preview>
  </interface>

  <progress>
    <phases>Upload, analysis, conversion, finalisation and completion.</phases>
    <bar>
      Use a prominent panel with a coloured bar and large percentage.
      Explicitly identify the phase to which the percentage refers.
    </bar>
    <upload>
      Read real progress from the request's upload progress event.
      Show bytes transferred and total, speed, elapsed time and estimated
      remaining time when it can be calculated.
    </upload>
    <analysis>
      Show an indeterminate state while checking the file; do not invent
      percentages.
    </analysis>
    <conversion>
      Run FFmpeg in a background PHP CLI worker. Read its output through
      -progress and calculate progress against the duration of the requested
      segment. Show processed and total duration, speed relative to real
      time, elapsed time and estimated remaining time. Present remaining
      time as a changing estimate. Do not show 100% until FFmpeg exits
      successfully and the result has been verified.
    </conversion>
    <robustness>
      Update state files atomically so JSON is never partial. Do not overlap
      polling requests. Distinguish a conversion error from a lost
      connection: if polling fails, warn that the server-side job may still
      be running. Prevent duplicate starts while a job is active. Never let
      a click go without visible feedback.
    </robustness>
  </progress>

  <diagnostics>
    On startup, check:
    - Compatible PHP version.
    - Extensions and functions that are actually required.
    - Presence and version of FFmpeg and FFprobe.
    - Availability of the required encoders.
    - Write access to logs, working-data and output folders.
    - PHP process identity.
    - Effective PHP upload limits.

    If something is missing, provide concrete instructions without
    installing packages. Distinguish checks run in the preview from those
    run under Apache.
  </diagnostics>

  <large_files>
    For the local installation, configure an 8 GiB file limit and a slightly
    larger POST limit. Also check Apache limits and timeouts. Apply settings
    only to this app when possible. Handle both mod_php and PHP-FPM without
    adding directives that are incompatible with the active handler.

    Report effective limits to the frontend and check file size before
    upload. Explicitly handle requests that are too large, incomplete
    uploads, insufficient disk space and non-JSON responses. Show a useful
    message instead of a generic connection error. Never read multi-gigabyte
    videos entirely into memory.
  </large_files>

  <history>
    Record job start, completion and errors in daily text files inside
    logs/, without a database. A JSON line per event is acceptable.
    Include the date, source name, destination, final size and any relevant
    error. Show a readable history of the latest 100 events in the
    interface. Do not present raw JSON as the normal interface.
  </history>

  <local_security>
    Limit HTTP access to local use. Deny direct HTTP access to logs/, working
    data, output, workers, internal libraries and installation scripts.
    Do not rely only on .htaccess: protection must work even when
    AllowOverride None is set.

    Do not allow arbitrary command execution. Pass FFmpeg arguments safely
    and validate all options. Protect state-changing requests against CSRF.
    Escape content shown in the interface. Remove temporary copies when a
    job ends, including on error. Never delete original sources or existing
    results.
  </local_security>

  <suggested_structure>
    index.php: interface.
    api.php: diagnostics, start, status, folder and history.
    lib.php: validation, FFprobe, command building and utilities.
    worker.php: conversion and real progress.
    router.php: protections for PHP preview server.
    assets/: Bootstrap, jQuery, CSS, JavaScript and licences.
    logs/: daily history.
    var/: temporary uploads and job state.
    output/: default destination.
    install.sh: installation verified under Apache.
    update-interface.sh: update application files with a backup.
    README.md: instructions, limits and checks.
  </suggested_structure>

  <workflow>
    Inspect the environment before changing files.
    Do not keep an old draft as a project constraint.
    Do not ask again for decisions already included in this prompt.
    Make ordinary implementation choices independently.

    Open a preview in a Codex panel or tab as soon as possible.
    State what is operational and what is only a visual representation.
    Do not publish the app on the Internet or use external hosting.

    If privileged installation is impossible, complete and test the
    workspace and leave one clear manual step. Do not claim that the actual
    installation has been verified unless you have checked it.
  </workflow>

  <testing>
    Use small synthetic video and audio files; do not depend on personal
    files. Verify:
    - PHP, JavaScript and shell-script syntax.
    - Real conversion and resulting codecs with FFprobe.
    - Resizing, cropping and trimming.
    - Audio extraction and normalisation.
    - Real intermediate percentages and 100% only when the result is ready.
    - FFmpeg errors without false completion.
    - Automatic filename, manual edits and extension.
    - Filename collisions without changing existing files.
    - Rejection of names containing paths.
    - Actual write and remove check.
    - Explicit rejection of oversized uploads.
    - HTTP protection of logs and internal files.
    - 1280x640 layout with preview and progress visible.
    - Dialog behaviour and accessibility of invalid fields.

    Remove temporary test files and pages. Document checks that could not
    be run.
  </testing>

  <deliverables>
    Deliver the working project, an openable preview, installation and
    update scripts, and a concise README. Summarise the checks performed
    and any remaining manual steps.
  </deliverables>
</prompt>
