<?php
require_once __DIR__.'/../tracking.php';
emsListenerHeaders(); header('Content-Type: application/json');
$db=null; $locked=false;
try {
    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'GET') { header('Allow: GET'); http_response_code(405); echo '{"error":"method_not_allowed"}'; exit; }
    $host=emsListenerHost(); $registered=false;
    foreach (emsTrackingConfig()['accounts'] as $profile) if ($profile['tracking_host']===$host) $registered=true;
    $secret=(string)getenv('TRACKING_REPORT_BEARER');
    if (!$registered || strlen($secret)<43 || strlen($secret)>256
        || !hash_equals('Bearer '.$secret,(string)($_SERVER['HTTP_AUTHORIZATION']??''))) {
        http_response_code(401); echo '{"error":"unauthorized"}'; exit;
    }
    if (getenv('TRACKING_REPORTING')!=='1') throw new RuntimeException('tracking_reporting_not_enabled');
    $scope=[];
    foreach (['organization_id','campaign_id','hours'] as $field) {
        $value=$_GET[$field]??'';
        if (!is_string($value) || !preg_match('/^[1-9][0-9]{0,9}$/D',$value)
            || filter_var($value,FILTER_VALIDATE_INT,['options'=>['min_range'=>1,'max_range'=>2147483647]])===false) throw new RuntimeException('tracking_report_scope_invalid');
        $scope[$field]=(int)$value;
    }
    if (!in_array($scope['hours'],[1,24],true)) throw new RuntimeException('tracking_report_window_invalid');
    $end=new DateTimeImmutable('now',new DateTimeZone('UTC')); $start=$end->modify('-'.$scope['hours'].' hours');
    $db=emsListenerDb();
    $s=$db->query("SELECT GET_LOCK('ems:tracking_raw_report',0)");
    if ((int)$s->fetchColumn()!==1) throw new RuntimeException('tracking_report_busy');
    // MariaDB 11.4.5 measures statement time in seconds (MySQL uses ms).
    $locked=true; $db->exec('SET SESSION max_statement_time=2');
    // One indexed bounded snapshot; no telemetry cursor, replay or opt-out ACK.
    $s=$db->prepare('SELECT kind,account_id,lead_id,link_id,link_key_id,destination_origin FROM tracking_raw_events FORCE INDEX (idx_tracking_raw_report)
        WHERE organization_id=? AND campaign_id=? AND is_test=0 AND observed_at_utc>=? AND observed_at_utc<? ORDER BY observed_at_utc,id LIMIT 10001');
    $s->execute([$scope['organization_id'],$scope['campaign_id'],$start->format('Y-m-d H:i:s.u'),$end->format('Y-m-d H:i:s.u')]);
    $rows=$s->fetchAll(PDO::FETCH_ASSOC); $complete=count($rows)<=10000;
    $totals=['raw_opens'=>0,'raw_clicks'=>0]; $opened=[]; $clicked=[]; $links=[];
    foreach (array_slice($rows,0,10000) as $row) {
        $lead=$row['account_id'].':'.$row['lead_id'];
        if ($row['kind']==='open') { $totals['raw_opens']++; $opened[$lead]=true; continue; }
        if ($row['kind']!=='click' || !preg_match('/^[a-f0-9]{64}$/D',(string)$row['link_id'])
            || !preg_match('/^[a-zA-Z0-9_-]{1,24}$/D',(string)$row['link_key_id'])) throw new RuntimeException('tracking_report_record_invalid');
        $totals['raw_clicks']++; $clicked[$lead]=true; $key=$row['account_id'].':'.$row['link_key_id'].':'.$row['link_id'];
        if (!isset($links[$key])) $links[$key]=['account_id'=>(int)$row['account_id'],'link_id'=>$row['link_id'],
            'link_key_id'=>$row['link_key_id'],'destination_origin'=>$row['destination_origin'],'raw_clicks'=>0,'leads'=>[]];
        if ($links[$key]['destination_origin']!==$row['destination_origin']) throw new RuntimeException('tracking_report_record_conflict');
        $links[$key]['raw_clicks']++; $links[$key]['leads'][$lead]=true;
    }
    uasort($links,static fn($a,$b)=>($b['raw_clicks']<=>$a['raw_clicks']) ?: strcmp($a['link_id'],$b['link_id']));
    $details=[];
    foreach (array_slice($links,0,50,true) as $link) { $link['distinct_lead_scopes']=count($link['leads']); unset($link['leads']); $details[]=$link; }
    $totals['distinct_open_lead_scopes']=count($opened); $totals['distinct_click_lead_scopes']=count($clicked);
    echo json_encode(['version'=>1,'stream_id'=>emsTrackingConfig()['stream_id'],'organization_id'=>$scope['organization_id'],
        'campaign_id'=>$scope['campaign_id'],'hours'=>$scope['hours'],'window_start_utc'=>$start->format('Y-m-d\TH:i:s.u\Z'),
        'window_end_utc'=>$end->format('Y-m-d\TH:i:s.u\Z'),'window_complete'=>$complete,'row_limit'=>10000,
        'rows_examined'=>min(10000,count($rows)),'totals'=>$totals,'links'=>$details,'links_truncated'=>count($links)>50,
        'human_verification_status'=>'not_established','verified_human_engagement'=>null,
        'source'=>'authenticated_context_raw_observations','legacy_data_included'=>false,'test_data_included'=>false],JSON_THROW_ON_ERROR);
} catch (Throwable $e) { error_log('tracking_observation_report_unavailable'); http_response_code(503); echo '{"error":"unavailable"}'; }
finally { if ($locked) { try { $db->query("SELECT RELEASE_LOCK('ems:tracking_raw_report')"); } catch (Throwable $ignored) {} } }
