#!/usr/bin/env bash
set -u
set -o pipefail

APP="/home/itouchdigitalin/public_html/app"
PHP="/opt/cpanel/ea-php82/root/usr/bin/php"
OUT="/home/itouchdigitalin/hardik-current-campaign-state-v2.txt"

cd "$APP" || exit 1
exec > >(tee "$OUT") 2>&1

echo "=============================================================="
echo " HARDIK CURRENT CAMPAIGN STATE V2 - READ ONLY"
echo "=============================================================="
echo "Generated: $(date '+%Y-%m-%d %H:%M:%S %Z')"

"$PHP" artisan tinker --execute='
use App\Modules\Broadcasting\Models\Campaign;
use Illuminate\Support\Facades\DB;

$client = \App\Models\Client::query()
    ->whereRaw("LOWER(name) LIKE ?", ["%hardik%"])
    ->with("workspaces")
    ->first();

if (!$client) {
    echo "HARDIK_CLIENT_NOT_FOUND".PHP_EOL;
    return;
}

$workspaceIds = $client->workspaces->pluck("id");

echo "CLIENT_ID=".$client->id.PHP_EOL;
echo "CLIENT_NAME=".$client->name.PHP_EOL;
echo "WORKSPACES=".$workspaceIds->join(",").PHP_EOL;
echo "APP_NOW=".now()->toIso8601String().PHP_EOL;

foreach (
    Campaign::query()
        ->whereIn("workspace_id", $workspaceIds)
        ->orderByDesc("id")
        ->limit(30)
        ->get()
    as $c
) {
    $counts = $c->recipients()
        ->selectRaw("status, COUNT(*) cnt")
        ->groupBy("status")
        ->pluck("cnt","status")
        ->toArray();

    $due = $c->schedule_at && $c->schedule_at->lte(now());

    echo PHP_EOL.
        "CAMPAIGN id=".$c->id.
        " uuid=".$c->uuid.
        " name=".str_replace(["\r","\n"]," ",$c->name).
        PHP_EOL;

    echo "  status=".$c->status.
        " channel=".$c->channel.
        " created_at=".$c->created_at?->toIso8601String().
        " updated_at=".$c->updated_at?->toIso8601String().
        PHP_EOL;

    echo "  schedule_at=".($c->schedule_at?->toIso8601String() ?: "NULL").
        " timezone=".($c->timezone ?: "NULL").
        " due_now=".($due ? "YES" : "NO").
        PHP_EOL;

    echo "  recipients=".json_encode($counts).
        " total=".$c->recipients()->count().
        PHP_EOL;

    if ($c->schedule_at && $c->status === "draft") {
        echo "  FLAG=SCHEDULE_SET_BUT_STATUS_DRAFT".PHP_EOL;
    }

    if ($due && $c->status === "queued") {
        echo "  FLAG=OVERDUE_QUEUED_NOT_LAUNCHED".PHP_EOL;
    }

    if ($c->status === "sending") {
        echo "  FLAG=SENDING pending_recipients=".
            $c->recipients()->where("status","queued")->count().
            PHP_EOL;
    }

    if ($c->recipients()->where("status","failed")->exists()) {
        $reasons = $c->recipients()
            ->where("status","failed")
            ->selectRaw("COALESCE(failed_reason,\"NULL\") reason, COUNT(*) cnt")
            ->groupBy("reason")
            ->orderByDesc("cnt")
            ->limit(8)
            ->pluck("cnt","reason")
            ->toArray();

        echo "  FAILED_REASONS=".json_encode($reasons).PHP_EOL;
    }
}

echo PHP_EOL."===== SUMMARY FLAGS =====".PHP_EOL;

echo "DUE_DRAFT=".
    Campaign::query()
        ->whereIn("workspace_id",$workspaceIds)
        ->where("status","draft")
        ->whereNotNull("schedule_at")
        ->where("schedule_at","<=",now())
        ->count().
    PHP_EOL;

echo "DUE_QUEUED=".
    Campaign::query()
        ->whereIn("workspace_id",$workspaceIds)
        ->where("status","queued")
        ->whereNotNull("schedule_at")
        ->where("schedule_at","<=",now())
        ->count().
    PHP_EOL;

echo "SENDING=".
    Campaign::query()
        ->whereIn("workspace_id",$workspaceIds)
        ->where("status","sending")
        ->count().
    PHP_EOL;

echo "BROADCAST_PENDING=".
    DB::table("jobs")->where("queue","broadcast")->count().
    PHP_EOL;

echo "FAILED_BROADCAST=".
    DB::table("failed_jobs")->where("queue","broadcast")->count().
    PHP_EOL;
'

echo
echo "===== CURRENT LAUNCH METHOD ====="
python3 - <<'PY'
from pathlib import Path
import re

p = Path("app/Modules/Broadcasting/Http/Controllers/CampaignController.php")
s = p.read_text()

start = s.find("public function launch")
if start == -1:
    print("LAUNCH_METHOD_NOT_FOUND")
else:
    print(s[start:start+6500])
PY

echo
echo "===== SCHEDULER DETECTOR ====="
sed -n '1,100p' app/Modules/Broadcasting/Jobs/LaunchScheduledCampaignsJob.php

echo
echo "===== WORKER / CRON ====="
systemctl is-active itouch-broadcast-queue.service 2>/dev/null || true
systemctl is-enabled itouch-broadcast-queue.service 2>/dev/null || true

ps -eo user,pid,etime,args \
    | grep '[a]rtisan queue:work database --queue=broadcast' \
    | grep -v grep || true

crontab -u itouchdigitalin -l 2>/dev/null \
    | grep '/home/itouchdigitalin/public_html/app.*schedule:run' \
    || true

echo
echo "===== RECENT CAMPAIGN LOGS ====="
grep -Ei \
    'campaign\.|LaunchCampaignJob|DispatchCampaignChunkJob|SendCampaignMessageJob' \
    storage/logs/laravel.log 2>/dev/null \
    | tail -200 || true

echo
echo "=============================================================="
echo " AUDIT COMPLETE"
echo "=============================================================="
echo "Report: $OUT"
echo "No campaign was modified or dispatched."
