<?php

namespace MintyPHP\Tests\Architecture;

use PHPUnit\Framework\TestCase;

class AgentSystemCatalogContractTest extends TestCase
{
    use AgentSystemContractSupport;
    use ProjectFileAssertionSupport;

    public function testGuardCatalogIdsAreUniqueAndWellFormed(): void
    {
        $catalog = $this->decodeAgentJson('.agents/checks/guard-catalog.json');
        $guards = is_array($catalog['guards'] ?? null) ? $catalog['guards'] : [];
        $this->assertNotSame([], $guards, 'Guard catalog must not be empty.');

        $ids = [];
        foreach ($guards as $guard) {
            $id = (string) ($guard['id'] ?? '');
            $reviewer = (string) ($guard['reviewer'] ?? '');
            $this->assertMatchesRegularExpression('/^GR-(CORE|TEST|UI|SEC)-[A-Z0-9]{3,}$/', $id, 'Invalid guard id: ' . $id);
            $this->assertContains($reviewer, ['code', 'security'], 'Invalid reviewer for ' . $id);
            $ids[] = $id;
        }

        $this->assertSame($ids, array_values(array_unique($ids)), 'Duplicate guard IDs found.');
    }

    public function testGuardCatalogReviewerAssignment(): void
    {
        $catalog = $this->decodeAgentJson('.agents/checks/guard-catalog.json');
        $guards = is_array($catalog['guards'] ?? null) ? $catalog['guards'] : [];

        foreach ($guards as $guard) {
            $id = (string) ($guard['id'] ?? '');
            $reviewer = (string) ($guard['reviewer'] ?? '');

            if (str_starts_with($id, 'GR-SEC-')) {
                $this->assertSame('security', $reviewer, $id . ' must be assigned to security reviewer');
            } else {
                $this->assertSame('code', $reviewer, $id . ' must be assigned to code reviewer');
            }
        }
    }

    public function testQualityGateIdsAreUniqueAndWellFormed(): void
    {
        $gates = $this->decodeAgentJson('.agents/checks/quality-gates.json');
        $items = is_array($gates['gates'] ?? null) ? $gates['gates'] : [];
        $this->assertNotSame([], $items, 'Quality gates must not be empty.');

        $ids = [];
        foreach ($items as $gate) {
            $id = (string) ($gate['id'] ?? '');
            $command = (string) ($gate['command'] ?? '');
            $this->assertMatchesRegularExpression('/^QG-[0-9]{3}$/', $id, 'Invalid quality gate id: ' . $id);
            $this->assertNotSame('', trim($command), 'Missing command for ' . $id);
            $ids[] = $id;
        }

        $this->assertSame($ids, array_values(array_unique($ids)), 'Duplicate quality gate IDs found.');
    }
}
