<?php

namespace App\Console\Commands;

use App\Services\NotionService;
use Illuminate\Console\Command;

class SetupManifest extends Command
{
    protected $signature = 'manifest:setup
                            {rootPageId : ID of the "The Manifest" page created manually in Notion}
                            {--skip-schema : Do not add tracking properties to the Tasks database}';

    protected $description = 'Create The Manifest section pages in Notion, add tracking properties to the Tasks database and update .env';

    public function __construct(private readonly NotionService $notion)
    {
        parent::__construct();
    }

    public function handle(): int
    {
        $rootId = $this->argument('rootPageId');

        // ── 1. Sanity check: integration can read the root page ──────────────
        $this->line('Checking access to the root page...');
        try {
            $this->notion->getPage($rootId);
        } catch (\Throwable $e) {
            $this->error('Cannot access that page. Open it in Notion → "..." → Connections → add this integration.');
            $this->line('  ' . $e->getMessage());
            return Command::FAILURE;
        }

        // ── 2. Create the two sections ────────────────────────────────────────
        $this->line('Creating "🔒 Documentação Técnica" (dev-only section)...');
        $technical = $this->notion->createPage(
            parentId: $rootId,
            title:    '🔒 Documentação Técnica',
            content:  [$this->paragraph(
                'Documentação técnica gerada automaticamente pelo Claude a partir das tasks concluídas. ' .
                'Restrita ao time de desenvolvimento — não compartilhe esta seção publicamente.'
            )]
        );

        $this->line('Creating "📖 Release Notes" (public/user section)...');
        $releases = $this->notion->createPage(
            parentId: $rootId,
            title:    '📖 Release Notes',
            content:  [$this->paragraph(
                'Notas de versão em linguagem de usuário, publicadas ao fim de cada sprint. ' .
                'Esta seção alimenta o site público The Manifest.'
            )]
        );

        // ── 3. Add tracking properties to the Tasks database ─────────────────
        if (! $this->option('skip-schema')) {
            $this->line('Adding tracking properties to the Tasks database...');
            try {
                $this->notion->updateDatabaseSchema(config('services.notion.tasks_database_id'), [
                    'Documentation Status' => ['select' => ['options' => [
                        ['name' => 'Pending',   'color' => 'gray'],
                        ['name' => 'Generated', 'color' => 'blue'],
                        ['name' => 'Published', 'color' => 'green'],
                    ]]],
                    'Technical Doc' => ['url' => new \stdClass()],
                    'Release Note'  => ['url' => new \stdClass()],
                ]);
                $this->info('  Properties added: Documentation Status, Technical Doc, Release Note.');
            } catch (\Throwable $e) {
                $this->warn('  Could not update Tasks database schema (is it shared with this integration?).');
                $this->line('  ' . $e->getMessage());
            }
        }

        // ── 4. Persist the IDs in .env ────────────────────────────────────────
        $this->writeEnv([
            'NOTION_MANIFEST_ROOT_PAGE_ID'    => $rootId,
            'NOTION_TECHNICAL_PARENT_PAGE_ID' => $technical['id'],
            'NOTION_RELEASES_PARENT_PAGE_ID'  => $releases['id'],
        ]);

        $this->newLine();
        $this->info('The Manifest is set up!');
        $this->table(['Section', 'Notion URL'], [
            ['Root',                $this->pageUrl($rootId)],
            ['Documentação Técnica', $technical['url'] ?? ''],
            ['Release Notes',        $releases['url'] ?? ''],
        ]);
        $this->line('Next: php artisan config:clear && php artisan queue:work');

        return Command::SUCCESS;
    }

    private function paragraph(string $text): array
    {
        return [
            'object'    => 'block',
            'type'      => 'paragraph',
            'paragraph' => ['rich_text' => [['type' => 'text', 'text' => ['content' => $text]]]],
        ];
    }

    private function pageUrl(string $id): string
    {
        return 'https://notion.so/' . str_replace('-', '', $id);
    }

    private function writeEnv(array $values): void
    {
        $envPath = base_path('.env');
        $env     = file_get_contents($envPath);

        foreach ($values as $key => $value) {
            $env = preg_match("/^{$key}=.*$/m", $env)
                ? preg_replace("/^{$key}=.*$/m", "{$key}={$value}", $env)
                : $env . PHP_EOL . "{$key}={$value}";
        }

        file_put_contents($envPath, $env);
        $this->info('  .env updated with the Notion page IDs.');
    }
}
