#!/usr/bin/env php
<?php
// Gimlet Tracker, command line. Run it as the web server's user (the installed command does that).
//   projects [STATUS|all]                     list projects (default: active and paused)
//   project SLUG                              one project and its open items
//   items SLUG [open|closed|all]              a project's items
//   open                                      every open item, all projects
//   mine                                      waiting on the owner, reminders due, reports to look at
//   show ID                                   one item with its links, files and notes
//   add SLUG KIND "TITLE" [--details T] [--priority P] [--status S] [--on owner|other] [--remind DATE] [--public yes]
//   note ID "TEXT" [--status S] [--on owner|other] [--fixed-in VERSION] [--by NAME]
//   set ID STATUS ["NOTE"] [--on owner|other] [--fixed-in VERSION] [--by NAME]
//   edit ID [--title T] [--details D] [--kind K] [--priority P] [--fixed-in V] [--public yes|no]
//   remind ID DATE|none                       a reminder on that day (YYYY-MM-DD)
//   link ID KIND OTHER-ID                     KIND parity|related|blocks|duplicate (ID blocks / duplicates OTHER)
//   unlink ID OTHER-ID                        remove the links between two items
//   attach ID FILE [NAME]                     add a screenshot or file to an item
//   changelog SLUG [VERSION]                  release notes from the "fixed in" versions
//   newproject SLUG "NAME" [--status S] [--summary T] [--location L] [--url U] [--version V]
//   editproject SLUG [--name N] [--status S] [--summary T] [--location L] [--url U] [--version V] [--public yes|no] [--reports yes|no]
//   digest [--dry-run] [--hours N]            the daily summary email (sent only when there is something to say)
//   mailtest                                  send a test email
//   passwd [NAME]                             set the login (asks for the password twice)
//   settings                                  show the settings in use
// KIND bug|feature|task|idea  STATUS new|open|planned|progress|waiting|done|wontdo  PRIORITY high|normal|low
// Copyright (C) 2026 Michael Slater. SPDX-License-Identifier: GPL-2.0-or-later
declare(strict_types=1);
require_once dirname(__DIR__) . '/lib/db.php';
require_once dirname(__DIR__) . '/lib/mail.php';

function out(string $s = ''): void { echo $s, "\n"; }
function fail(string $s): never { fwrite(STDERR, $s . "\n"); exit(1); }
function opts(array &$args): array
{
    $o = [];
    for ($i = 0; $i < count($args); $i++) {
        if ($args[$i] === '--dry-run') { $o['dry-run'] = '1'; array_splice($args, $i, 1); $i--; continue; }
        if (str_starts_with($args[$i], '--')) {
            $o[substr($args[$i], 2)] = $args[$i + 1] ?? fail('Missing value after ' . $args[$i]);
            array_splice($args, $i, 2); $i--;
        }
    }
    return $o;
}
function need_project(string $slug): array { return project_by_slug($slug) ?? fail("No project $slug. Try: " . setting('command_name') . ' projects all'); }
function on_value(?string $v): string { return match ((string)$v) { '', 'none' => '', 'me', 'owner', 'michael' => 'owner', default => (string)$v }; }
function item_line(array $i): string
{
    $st = $i['status'] === 'waiting' && $i['waiting_on'] !== '' ? ($i['waiting_on'] === 'owner' ? 'Waiting(me)' : 'Waiting') : ITEM_STATUS[$i['status']];
    return sprintf("#%-4d %-8s %-11s %s%s%s%s", $i['id'], ITEM_KIND[$i['kind']], $st, $i['priority'] !== 'normal' ? '[' . strtoupper($i['priority']) . '] ' : '', $i['title'],
        $i['fixed_in'] !== '' ? '  (fixed in ' . $i['fixed_in'] . ')' : '', $i['remind_on'] !== '' ? '  (remind ' . $i['remind_on'] . ')' : '');
}
function list_items(array $rows, bool $slug = false): void { foreach ($rows as $i) out(($slug ? str_pad($i['pslug'] ?? '', 20) . ' ' : '') . item_line($i)); }

$args = array_slice($argv, 1);
$o = opts($args);
$cmd = $args[0] ?? 'help';
$by = $o['by'] ?? 'Claude';
try {
    switch ($cmd) {
        case 'projects':
            $which = $args[1] ?? '';
            $sql = $which === 'all' ? 'SELECT * FROM projects ORDER BY status, name' : ($which !== '' ? 'SELECT * FROM projects WHERE status = ? ORDER BY name' : "SELECT * FROM projects WHERE status IN ('active','paused') ORDER BY status, name");
            $counts = project_counts();
            foreach (q($sql, $which !== '' && $which !== 'all' ? [$which] : [])->fetchAll() as $p) {
                $c = $counts[$p['id']] ?? ['open' => 0, 'progress' => 0, 'closed' => 0];
                out(sprintf('%-22s %-9s %3d open %2d in progress %3d closed  %s%s', $p['slug'], $p['status'], $c['open'], $c['progress'], $c['closed'], $p['name'], (int)$p['public'] ? '  [public]' : ''));
            }
            break;
        case 'project':
            $p = need_project($args[1] ?? fail('project SLUG'));
            out($p['name'] . ' (' . $p['slug'] . ', ' . $p['status'] . ($p['version'] !== '' ? ', ' . $p['version'] : '') . ((int)$p['public'] ? ', public page' . ((int)$p['reports'] ? ' + reports' : '') : '') . ')');
            if ($p['location'] !== '') out('Lives in: ' . $p['location']);
            if ($p['url'] !== '') out('Web: ' . $p['url']);
            if ($p['summary'] !== '') out($p['summary']);
            out();
            list_items(q("SELECT * FROM items i WHERE project_id = ? AND " . OPEN_SQL . ' ' . ITEM_ORDER, [$p['id']])->fetchAll());
            break;
        case 'items':
            $p = need_project($args[1] ?? fail('items SLUG'));
            $w = $args[2] ?? 'open';
            $cond = $w === 'all' ? '' : ($w === 'closed' ? "AND i.status IN ('done','wontdo')" : 'AND ' . OPEN_SQL);
            list_items(q("SELECT * FROM items i WHERE project_id = ? $cond ORDER BY id", [$p['id']])->fetchAll());
            break;
        case 'open':
            list_items(q("SELECT i.*, p.slug pslug FROM items i JOIN projects p ON p.id = i.project_id WHERE " . OPEN_SQL . " ORDER BY p.slug, i.id")->fetchAll(), true);
            break;
        case 'mine':
            $n = needs_owner();
            foreach (['due' => 'Reminders due', 'waiting' => 'Waiting on ' . owner_name(), 'reports' => 'Reports to look at'] as $k => $head) {
                out("$head (" . count($n[$k]) . ')');
                foreach ($n[$k] as $i) out('  ' . str_pad($i['pname'], 22) . ' ' . item_line($i));
                out();
            }
            break;
        case 'show':
            $i = item((int)($args[1] ?? 0)) ?? fail('No such item.');
            $p = project((int)$i['project_id']);
            out(item_line($i) . '   (' . $p['slug'] . ', added ' . $i['created'] . ' UTC' . ($i['added_by'] !== '' ? ' by ' . $i['added_by'] : '') . ((int)$i['public'] ? ', public' : '') . ')');
            if ($i['reporter'] !== '') out('Reported by: ' . $i['reporter']);
            if ($i['details'] !== '') out("\n" . $i['details']);
            $links = item_links((int)$i['id']);
            if ($links) { out("\nLinks:"); foreach ($links as [, $label, $x]) out("  $label #" . $x['id'] . ' ' . $x['title'] . ' (' . $x['pslug'] . ', ' . ITEM_STATUS[$x['status']] . ')'); }
            $files = q('SELECT * FROM attachments WHERE item_id = ? ORDER BY id', [$i['id']])->fetchAll();
            if ($files) { out("\nFiles:"); foreach ($files as $f) out('  ' . $f['name'] . ' (' . $f['size'] . ' bytes, ' . attachment_path((int)$f['id']) . ')'); }
            foreach (q('SELECT * FROM notes WHERE item_id = ? ORDER BY id', [$i['id']])->fetchAll() as $n)
                out("\n-- " . $n['author'] . ', ' . $n['created'] . ' UTC' . ($n['status_to'] ? ': ' . ITEM_STATUS[$n['status_from']] . ' -> ' . ITEM_STATUS[$n['status_to']] : '') . ($n['text'] !== '' ? "\n" . $n['text'] : ''));
            break;
        case 'add':
            $p = need_project($args[1] ?? fail('add SLUG KIND "TITLE"'));
            $id = add_item((int)$p['id'], ['kind' => $args[2] ?? 'feature', 'title' => $args[3] ?? '', 'details' => $o['details'] ?? '', 'priority' => $o['priority'] ?? 'normal',
                'status' => $o['status'] ?? 'open', 'waiting_on' => on_value($o['on'] ?? ''), 'remind_on' => $o['remind'] ?? '', 'public' => $o['public'] ?? '0', 'fixed_in' => $o['fixed-in'] ?? ''], $by);
            out("Added #$id");
            break;
        case 'note':
            add_note((int)($args[1] ?? 0), $by, $args[2] ?? '', $o['status'] ?? null, ['waiting_on' => on_value($o['on'] ?? ''), 'fixed_in' => $o['fixed-in'] ?? '']);
            out('Saved.');
            break;
        case 'set':
            add_note((int)($args[1] ?? 0), $by, $args[3] ?? '', $args[2] ?? fail('set ID STATUS ["NOTE"]'), ['waiting_on' => on_value($o['on'] ?? ''), 'fixed_in' => $o['fixed-in'] ?? '']);
            out('Saved.');
            break;
        case 'edit':
            $f = [];
            foreach (['title', 'details', 'kind', 'priority', 'public'] as $k) if (isset($o[$k])) $f[$k] = $o[$k];
            if (isset($o['fixed-in'])) $f['fixed_in'] = $o['fixed-in'];
            if (isset($o['on'])) $f['waiting_on'] = on_value($o['on']);
            update_item((int)($args[1] ?? 0), $f);
            out('Saved.');
            break;
        case 'remind':
            $d = $args[2] ?? fail('remind ID DATE|none');
            update_item((int)($args[1] ?? 0), ['remind_on' => $d === 'none' ? '' : $d]);
            out($d === 'none' ? 'Reminder cleared.' : "Reminder set for $d.");
            break;
        case 'link':
            $kind = $args[2] ?? fail('link ID KIND OTHER-ID');
            add_link((int)($args[1] ?? 0), (int)ltrim($args[3] ?? '', '#'), $kind);
            out('Linked.');
            break;
        case 'unlink':
            $a = (int)($args[1] ?? 0); $b = (int)ltrim($args[2] ?? '', '#');
            $n = q('DELETE FROM links WHERE (a = ? AND b = ?) OR (a = ? AND b = ?)', [$a, $b, $b, $a])->rowCount();
            out("Removed $n link(s).");
            break;
        case 'attach':
            $file = $args[2] ?? fail('attach ID FILE [NAME]');
            if (!is_file($file)) fail("No file $file");
            $fid = add_attachment((int)($args[1] ?? 0), $file, $args[3] ?? basename($file), $by);
            out("Attached as file $fid.");
            break;
        case 'changelog':
            $p = need_project($args[1] ?? fail('changelog SLUG [VERSION]'));
            $t = changelog_text($p, $args[2] ?? null);
            out($t !== '' ? rtrim($t) : 'No items with that "fixed in" version.');
            break;
        case 'newproject':
            $id = add_project(['slug' => $args[1] ?? '', 'name' => $args[2] ?? '', 'status' => $o['status'] ?? 'active', 'summary' => $o['summary'] ?? '', 'location' => $o['location'] ?? '', 'url' => $o['url'] ?? '', 'version' => $o['version'] ?? '', 'public' => $o['public'] ?? '0', 'reports' => $o['reports'] ?? '0']);
            out("Added project $id");
            break;
        case 'editproject':
            $p = need_project($args[1] ?? fail('editproject SLUG'));
            update_project((int)$p['id'], $o);
            out('Saved.');
            break;
        case 'digest':
            $t = digest_text((int)($o['hours'] ?? 24));
            if (isset($o['dry-run'])) { out($t !== '' ? $t : '(nothing to report: no email would be sent)'); break; }
            if ($t === '') break;
            send_mail(setting('title') . ': daily summary', $t, 'digest');
            out('Sent the summary to ' . setting('mail_to') . '.');
            break;
        case 'mailtest':
            send_mail(setting('title') . ': test message', "This is a test message from Gimlet Tracker " . TRACKER_VERSION . ".\nMail is set up correctly.\n", 'test');
            out('Sent a test message to ' . setting('mail_to') . '.');
            break;
        case 'passwd':
            $name = $args[1] ?? 'admin';
            if (!preg_match('/^[A-Za-z0-9_.-]{2,30}$/', $name)) fail('A name is 2 to 30 letters, digits, _ . -');
            if (getenv('TRACKER_PASSWORD') !== false) $pw = (string)getenv('TRACKER_PASSWORD');
            else {
                $read = function (string $prompt): string { fwrite(STDERR, $prompt); system('stty -echo 2>/dev/null'); $l = rtrim((string)fgets(STDIN), "\n"); system('stty echo 2>/dev/null'); fwrite(STDERR, "\n"); return $l; };
                $pw = $read("New password for $name: ");
                if ($read('Again: ') !== $pw) fail('They do not match. Nothing changed.');
            }
            if (strlen($pw) < 10) fail('A password needs 10 letters or more. Nothing changed.');
            $f = data_dir() . '/config.json';
            $c = is_file($f) ? (json_decode((string)file_get_contents($f), true) ?: []) : [];
            $c['user'] = $name; $c['hash'] = password_hash($pw, PASSWORD_DEFAULT);
            if (isset($o['display'])) $c['display'] = $o['display'];
            file_put_contents($f . '.new', json_encode($c, JSON_PRETTY_PRINT)); chmod($f . '.new', 0600); rename($f . '.new', $f);
            // log everyone out
            foreach (glob(data_dir() . '/sessions/sess_*') ?: [] as $s) @unlink($s);
            out("The login is now $name with the new password. Everyone was logged out.");
            break;
        case 'settings':
            foreach (settings() as $k => $v) out(str_pad($k, 16) . ' ' . ($k === 'smtp_password' && $v !== '' ? '(set)' : $v));
            out(str_pad('version', 16) . ' ' . TRACKER_VERSION);
            break;
        default:
            $src = file_get_contents(__FILE__);
            preg_match_all('~^// (.*)$~m', $src, $m);
            $name = setting('command_name');
            foreach (array_slice($m[1], 0, 26) as $l) out(str_starts_with($l, '  ') ? '  ' . $name . ' ' . ltrim($l) : $l);
    }
} catch (InputError | MailError $e) { fail($e->getMessage()); }
