<?php
// Shared, content-addressed storage; uploaded source is never executed.
declare(strict_types=1);
require_once __DIR__.'/student_projects.php';
function collaboration_get(array $user,int $id): array {
 $q=db()->prepare("SELECT p.*,".collaboration_name_sql()." AS full_name,u.username AS administrator_username FROM collaboration_projects p JOIN users u ON u.id=p.created_by WHERE p.id=? AND NOT EXISTS (SELECT 1 FROM collaboration_deleted_projects x WHERE x.project_id=p.id) AND (? IN ('admin','staff') OR EXISTS (SELECT 1 FROM collaboration_members m WHERE m.project_id=p.id AND m.user_id=?))");
 $q->execute([$id,$user['role'],$user['id']]);$p=$q->fetch();if(!$p)reply(404,['message'=>'Project not found or you are no longer a member.']);return $p;
}
function collaboration_stamp(array &$m,string $path,array $user,string $action): void {
 $now=gmdate('c');$name=trim((string)($user['full_name']??''))?:($user['username']??'Member');
 $stamp=['updated_at'=>$now,'updated_by'=>(int)$user['id'],'updated_by_name'=>$name,'change'=>$action];
 $m['files'][$path]=array_merge($m['files'][$path],$stamp);
 for($parent=dirname($path);$parent!=='.';$parent=dirname($parent)){
  if(isset($m['files'][$parent])&&!$m['files'][$parent]['directory'])throw new InvalidArgumentException('A parent path is already a file.');
  $m['files'][$parent]=array_merge(['directory'=>true,'size'=>0],$m['files'][$parent]??[],$stamp);
 }
 $m['updated_at']=$now;$m['updated_by']=(int)$user['id'];$m['updated_by_name']=$name;
 $m['activity'][]=array_merge(['path'=>$path],$stamp);
 // Keep the complete activity history in the manifest; return only recent events to the UI.
}
function collaboration_listing(array $m): array {return array_merge(project_listing($m),['updated_by_name'=>$m['updated_by_name']??null,'activity'=>array_map(static fn($event)=>array_diff_key($event,['before_blob'=>true,'after_blob'=>true]),array_reverse(array_slice($m['activity']??[],-100)))]);}
function collaboration_limits(array $files): void {
 if(count($files)>3000||array_sum(array_column($files,'size'))>PROJECT_TOTAL_LIMIT)throw new InvalidArgumentException('Project limit: 3,000 entries and 100 MB.');
 $seen=[];foreach($files as $path=>$entry){$key=strtolower((string)$path);if(isset($seen[$key]))throw new InvalidArgumentException('Names differing only by letter case are not supported.');$seen[$key]=true;}
}

/** Line-level ranges; line endings are kept so CRLF/trailing-newline edits are recorded. */
function collaboration_lines(string $text): array {return $text===''?[]:preg_split('/(?<=\n)/',$text,-1,PREG_SPLIT_NO_EMPTY);}
function collaboration_line_changes(string $before,string $after): array {
 $a=collaboration_lines($before);$b=collaboration_lines($after);$hunks=[];$budget=300000;
 $emit=static function(int $ai,int $an,int $bi,int $bn,bool $grouped=false)use(&$hunks): void {
  if($an||$bn)$hunks[]=['old_start'=>$ai+1,'old_count'=>$an,'new_start'=>$bi+1,'new_count'=>$bn,'grouped'=>$grouped];
 };
 $walk=function(int $lo,int $hi,int $bo,int $bh,int $depth=0)use(&$walk,&$a,&$b,&$budget,$emit): void {
  while($lo<$hi&&$bo<$bh&&$a[$lo]===$b[$bo]){$lo++;$bo++;}
  while($lo<$hi&&$bo<$bh&&$a[$hi-1]===$b[$bh-1]){$hi--;$bh--;}
  $n=$hi-$lo;$m=$bh-$bo;if(!$n||!$m){$emit($lo,$n,$bo,$m);return;}
  if($depth<12){
   // Patience anchors separate distant edits without allocating a quadratic matrix.
   $ac=[];$bc=[];for($i=$lo;$i<$hi;$i++){$k='l'.$a[$i];$ac[$k]=isset($ac[$k])?-1:$i;}for($j=$bo;$j<$bh;$j++){$k='l'.$b[$j];$bc[$k]=isset($bc[$k])?-1:$j;}
   $pairs=[];foreach($ac as $key=>$i)if($i>=0&&isset($bc[$key])&&$bc[$key]>=0)$pairs[]=[$i,$bc[$key]];
   if($pairs){$tails=[];$indices=[];$prev=[];foreach($pairs as $i=>$pair){$left=0;$right=count($tails);while($left<$right){$mid=intdiv($left+$right,2);if($tails[$mid]<$pair[1])$left=$mid+1;else $right=$mid;}$prev[$i]=$left?$indices[$left-1]:-1;$tails[$left]=$pair[1];$indices[$left]=$i;}$anchors=[];for($i=$indices[count($tails)-1];$i>=0;$i=$prev[$i])$anchors[]=$pairs[$i];$anchors=array_reverse($anchors);$x=$lo;$y=$bo;foreach($anchors as [$i,$j]){$walk($x,$i,$y,$j,$depth+1);$x=$i+1;$y=$j+1;}$walk($x,$hi,$y,$bh,$depth+1);return;}
  }
  if($n*$m>$budget){$emit($lo,$n,$bo,$m,true);return;}$budget-=$n*$m;
  $dp=array_fill(0,$n+1,array_fill(0,$m+1,0));for($i=$n-1;$i>=0;$i--)for($j=$m-1;$j>=0;$j--)$dp[$i][$j]=$a[$lo+$i]===$b[$bo+$j]?1+$dp[$i+1][$j+1]:max($dp[$i+1][$j],$dp[$i][$j+1]);
  $i=0;$j=0;$start=null;$flush=static function()use(&$start,$emit,&$i,&$j,$lo,$bo): void {if($start!==null){$emit($lo+$start[0],$i-$start[0],$bo+$start[1],$j-$start[1]);$start=null;}};
  while($i<$n||$j<$m){if($i<$n&&$j<$m&&$a[$lo+$i]===$b[$bo+$j]){$flush();$i++;$j++;}else{if($start===null)$start=[$i,$j];if($j<$m&&($i===$n||$dp[$i][$j+1]>$dp[$i+1][$j]))$j++;else $i++;}}$flush();
 };
 $walk(0,count($a),0,count($b));return $hunks;
}
function collaboration_history(array $m,string $path): array {
 $events=[];foreach($m['activity']??[] as $index=>$event)if($event['path']===$path){$safe=array_diff_key($event,['before_blob'=>true,'after_blob'=>true]);$safe['event_id']=$index;$safe['after_current']=isset($event['after_blob'])&&($m['files'][$path]['blob']??null)===$event['after_blob'];$events[]=$safe;}
 return array_reverse(array_slice($events,-100));
}
function collaboration_diff_preview(array $event,string $root): array {
 $before=collaboration_lines(file_get_contents($root.'/blobs/'.$event['before_blob']));$after=collaboration_lines(file_get_contents($root.'/blobs/'.$event['after_blob']));$out=[];$remaining=400;
 foreach($event['line_changes'] as $hunk){$item=$hunk;$item['removed']=[];$item['added']=[];foreach([['removed',$before,'old'],['added',$after,'new']] as [$key,$lines,$side]){for($i=0;$i<$hunk[$side.'_count']&&$remaining>0;$i++,$remaining--){$line=$hunk[$side.'_start']+$i;$text=$lines[$line-1]??'';$item[$key][]=['line'=>$line,'text'=>substr($text,0,2000),'truncated'=>strlen($text)>2000];}}$item['truncated']=count($item['removed'])<$hunk['old_count']||count($item['added'])<$hunk['new_count'];$out[]=$item;if(!$remaining)break;}
 return ['hunks'=>$out,'truncated'=>count($out)<count($event['line_changes'])||array_reduce($out,static fn($carry,$h)=>$carry||$h['truncated'],false)];
}

/** Remove a subtree from the live manifest; content blobs remain for the audit trail. */
function collaboration_delete(array &$m,string $path,array $user): int {
 $path=project_path($path);if(!isset($m['files'][$path]))throw new InvalidArgumentException('This file or folder no longer exists.');
 $removed=[];foreach($m['files'] as $name=>$entry)if($name===$path||str_starts_with((string)$name,$path.'/'))$removed[$name]=$entry;
 $directory=$m['files'][$path]['directory'];collaboration_stamp($m,$path,$user,$directory?'Deleted folder':'Deleted file');
 $index=count($m['activity'])-1;$m['activity'][$index]['removed_entries']=count($removed);$m['activity'][$index]['removed_paths']=array_keys($removed);
 foreach($removed as $name=>$entry)unset($m['files'][$name]);return count($removed);
}
function collaboration_name_sql(string $alias='u'): string {
 return "COALESCE(CASE WHEN LOWER(TRIM(COALESCE($alias.full_name,''))) IN ('','null','undefined') THEN NULL ELSE TRIM($alias.full_name) END,NULLIF(TRIM($alias.username),''),CONCAT('User #',$alias.id))";
}
function collaboration_department(array $user): ?int {
 $q=db()->prepare('SELECT department_id FROM collaboration_admin_departments WHERE user_id=?');$q->execute([$user['id']]);$id=$q->fetchColumn();return $id?(int)$id:null;
}
