<?php

namespace App\Console\Commands;

use App\Services\ClaudeService;
use App\Services\NotionService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class GenerateReleaseEmail extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'release:generate-email
                            {sprint : Sprint label, e.g. 2026-06}
                            {--dry-run : Preview without saving to Notion}
                            {--output= : Save HTML to a local file path}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate the sprint release email from all "Generated" Notion release notes';

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

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $sprint  = $this->argument('sprint');
        $dryRun  = $this->option('dry-run');
        $outFile = $this->option('output');

        $this->info("Generating release email for sprint: <comment>{$sprint}</comment>");

        // ── 1. Fetch release notes from the Tasks database ────────────────────
        $this->line('  Querying Notion Tasks database...');
        $releaseNotes = $this->notion->releaseNotesForSprint($sprint);

        if (empty($releaseNotes)) {
            $this->warn("No generated release notes found for sprint '{$sprint}'.");
            return Command::FAILURE;
        }

        $this->info('  Found ' . count($releaseNotes) . ' release note(s).');
        foreach ($releaseNotes as $note) {
            $this->line("  - [{$note['category']}] {$note['title']}");
        }

        // ── 2. Generate HTML via Claude ───────────────────────────────────────
        $this->line('  Calling Claude API...');
        $emailHtml = $this->claude->generateReleaseEmail($releaseNotes, $sprint);

        // ── 3. Save to Notion (unless dry-run) ───────────────────────────────
        if (! $dryRun) {
            $parentId = config('services.notion.releases_parent_page_id');
            $this->notion->createPage(
                parentId: $parentId,
                title:    "📧 Release Email — {$sprint}",
                content:  [
                    [
                        'object' => 'block',
                        'type'   => 'code',
                        'code'   => [
                            'language'  => 'html',
                            'rich_text' => [['type' => 'text', 'text' => ['content' => $emailHtml]]],
                        ],
                    ],
                ]
            );
            $this->info('  Saved to Notion.');
        } else {
            $this->warn('  Dry-run mode: not saved to Notion.');
        }

        // ── 4. Save to local file if requested ───────────────────────────────
        if ($outFile) {
            file_put_contents($outFile, $emailHtml);
            $this->info("  HTML saved to: {$outFile}");
        }

        $this->info('Done!');
        $this->line('');
        $this->line(
            "Add to scheduler in <info>app/Console/Kernel.php</info>:\n" .
            "  \$schedule->command('release:generate-email " . date('Y-m') . "')\n" .
            "           ->lastDayOfMonth('17:00');"
        );

        return Command::SUCCESS;
    }
}