<?php
// https://stackexchange.com/oauth/dialog?client_id=9796&scope=write_access&redirect_uri=https://stackexchange.com/oauth/login_success
$key = 'FIXME';
$access_token = 'FIXME';
$apiUrl = 'https://api.stackexchange.com/2.2/';
$site = 'stackoverflow';

require_once 'HTTP/Request2.php';

//search
// https://api.stackexchange.com/docs/search
$req = new HTTP_Request2(
    $apiUrl . 'search?' . http_build_query(
        [
            'key'          => $key,
            'access_token' => $access_token,
            'order'        => 'desc',
            'sort'         => 'activity',
            // https://api.stackexchange.com/docs/filters
            // filter must be "unsafe"!
            //'filter'       => 'withbody',
            'filter'       => ')peeUKlrI1gEM_K5k96Qk8IC',
            'site'         => $site,
            'intitle'      => 'javasript',//fix 1
            'intitle'      => 'javascipt',//fix 2
        ]
    )
);
$res = $req->send();

$data = json_decode($res->getBody());

foreach ($data->items as $question) {
    echo $question->question_id . "\n";
    echo ' ' . $question->link . "\n";

    if (file_exists(__DIR__ . '/fixed/' . $question->question_id)) {
        echo " already fixed\n";
        continue;
    }

    echo ' title: ' . $question->title . "\n";
    $fixed = str_replace(
        // fix 1: JavaSript
        //['javasript', 'Javasript', 'JavaSript', 'javaSript'],
        // fix 2: JavaScipt
        ['javascipt', 'Javascipt', 'JavaScipt', 'JavaScipt'],
        ['javascript', 'JavaScript', 'JavaScript', 'JavaScript'],
        $question->title
    );
    echo ' fixed: ' . $fixed . "\n";

    if ($fixed == $question->title) {
        echo " !! title did not change, skipping\n";
        continue;
    }
    //var_dump($question);die();

    // https://api.stackexchange.com/docs/edit-question
    // filter can be created there
    $wreq = new HTTP_Request2(
        $apiUrl . 'questions/' . $question->question_id . '/edit',
        'POST'
    );
    $wreq->addPostParameter('key', $key);
    $wreq->addPostParameter('access_token', $access_token);
    $wreq->addPostParameter('site', $site);
    $wreq->addPostParameter('title', $fixed);
    $wreq->addPostParameter('body', $question->body_markdown);
    $wreq->addPostParameter('tags', implode(',', $question->tags));
    $res = $wreq->send();
    if ($res->getStatus() == 200) {
        //mark fixed
        echo " fixed!\n";
        file_put_contents(
            __DIR__ . '/fixed/' . $question->question_id, ''
        );
        //echo $res->getBody() . "\n";//die();
        sleep(4);
        //exit(0);
    } else {
        echo "ERROR\n";
        echo $res->getBody() . "\n";
        exit(1);
    }
}
?>
