<?php
declare(strict_types=1);
require_once __DIR__.'/../shared/lib/project_collaborations.php';
function verify_diff(string $old,string $new): array {
 $hunks=collaboration_line_changes($old,$new);$actual=collaboration_lines($old);$target=collaboration_lines($new);
 foreach(array_reverse($hunks) as $h)array_splice($actual,$h['old_start']-1,$h['old_count'],array_slice($target,$h['new_start']-1,$h['new_count']));
 if(implode('',$actual)!==$new)throw new RuntimeException('Diff cannot reconstruct saved code.');return $hunks;
}
$h=verify_diff("first\nold\nlast\n","first\nnew\nlast\n");if(count($h)!==1||$h[0]['old_start']!==2||$h[0]['new_count']!==1)throw new RuntimeException('Wrong modified line');
$h=verify_diff("a\nb\nc\nd\ne\n","a\nB\nc\nD\ne\n");if(count($h)!==2)throw new RuntimeException('Separated changes not split');
foreach([['',''],['','one\n'],["one\n",''],["a\nb\n","a\nextra\nb\n"],["a\nb\nc\n","a\nc\n"],["a\n","a"],["a\r\nb\r\n","a\nb\n"]] as [$old,$new])verify_diff($old,$new);
mt_srand(42);for($i=0;$i<300;$i++){$a=[];$b=[];for($j=0;$j<mt_rand(0,40);$j++)$a[]=chr(97+mt_rand(0,6))."\n";for($j=0;$j<mt_rand(0,40);$j++)$b[]=chr(97+mt_rand(0,6))."\n";verify_diff(implode('',$a),implode('',$b));}
verify_diff(str_repeat("old\n",1500),str_repeat("new\n",1500));
$old=implode('',array_map(static fn($i)=>'line '.$i."\n",range(1,15000)));$new=str_replace(["line 20\n","line 14000\n"],["changed20\n","changed14000\n"],$old);$h=verify_diff($old,$new);if(count($h)!==2)throw new RuntimeException('Large-file separated edits');
$m=['files'=>['main.js'=>['blob'=>'new']], 'activity'=>[['path'=>'main.js','change'=>'Edited file','before_blob'=>'old','after_blob'=>'new','line_changes'=>$h]]];$history=collaboration_history($m,'main.js');if(isset($history[0]['before_blob'])||!$history[0]['after_current'])throw new RuntimeException('History filtering');
echo "PASS: exact line ranges, independent edits, insertion/deletion, newline changes, 300 randomized reconstructions, large-file diff limits and private history metadata.\n";
