<?php

class PremiumDiscountService
{
    /*
    |--------------------------------------------------------------------------
    | Build Institutional Dealing Range
    |--------------------------------------------------------------------------
    */

    public static function buildDealingRange(array $candles): array
    {
        if (empty($candles)) {
            return self::emptyRange();
        }

        $recent = array_slice($candles, -120);

        $high = max(array_map(
            fn($c) => (float)$c['high_price'],
            $recent
        ));

        $low = min(array_map(
            fn($c) => (float)$c['low_price'],
            $recent
        ));

        $equilibrium = ($high + $low) / 2;

        $premiumStart = $equilibrium;
        $premiumEnd = $high;

        $discountStart = $low;
        $discountEnd = $equilibrium;

        return [

            'range_high' => $high,

            'range_low' => $low,

            'equilibrium' => $equilibrium,

            'premium_zone' => [
                'low' => $premiumStart,
                'high' => $premiumEnd
            ],

            'discount_zone' => [
                'low' => $discountStart,
                'high' => $discountEnd
            ],

            'range_size' => abs($high - $low)
        ];
    }

    /*
    |--------------------------------------------------------------------------
    | Institutional Price Location
    |--------------------------------------------------------------------------
    */

    public static function determineLocation(
        float $price,
        array $range
    ): string {

        if (empty($range)) {
            return 'UNKNOWN';
        }

        $equilibrium = (float)$range['equilibrium'];

        $high = (float)$range['range_high'];

        $low = (float)$range['range_low'];

        $position = self::calculateRangePercentage(
            $price,
            $high,
            $low
        );

        if ($position >= 75) {
            return 'EXTREME PREMIUM';
        }

        if ($position >= 55) {
            return 'PREMIUM';
        }

        if ($position <= 25) {
            return 'EXTREME DISCOUNT';
        }

        if ($position <= 45) {
            return 'DISCOUNT';
        }

        return 'EQUILIBRIUM';
    }

    /*
    |--------------------------------------------------------------------------
    | Range Percentage
    |--------------------------------------------------------------------------
    */

    public static function calculateRangePercentage(
        float $price,
        float $high,
        float $low
    ): float {

        $range = $high - $low;

        if ($range <= 0) {
            return 50;
        }

        return round(
            (($price - $low) / $range) * 100,
            2
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Determine Institutional Directional Advantage
    |--------------------------------------------------------------------------
    */

    public static function directionalAdvantage(
        string $bias,
        string $location
    ): array {

        $favorable = false;

        $message = 'Neutral positioning';

        if (
            $bias === 'BUY' &&
            in_array($location, [
                'DISCOUNT',
                'EXTREME DISCOUNT'
            ])
        ) {

            $favorable = true;

            $message = 'Institutional BUY pricing advantage';
        }

        if (
            $bias === 'SELL' &&
            in_array($location, [
                'PREMIUM',
                'EXTREME PREMIUM'
            ])
        ) {

            $favorable = true;

            $message = 'Institutional SELL pricing advantage';
        }

        if (
            $bias === 'BUY' &&
            in_array($location, [
                'PREMIUM',
                'EXTREME PREMIUM'
            ])
        ) {

            $message = 'BUY setup in premium pricing area';
        }

        if (
            $bias === 'SELL' &&
            in_array($location, [
                'DISCOUNT',
                'EXTREME DISCOUNT'
            ])
        ) {

            $message = 'SELL setup in discount pricing area';
        }

        return [

            'favorable' => $favorable,

            'message' => $message
        ];
    }

    /*
    |--------------------------------------------------------------------------
    | Liquidity Draw Analysis
    |--------------------------------------------------------------------------
    */

    public static function determineDrawOnLiquidity(
        string $bias,
        array $liquidity
    ): array {

        if ($bias === 'BUY') {

            return [

                'target_side' => 'BUY SIDE',

                'target_price' => $liquidity['buy_side'] ?? null,

                'narrative' => 'Seeking external buy-side liquidity'
            ];
        }

        if ($bias === 'SELL') {

            return [

                'target_side' => 'SELL SIDE',

                'target_price' => $liquidity['sell_side'] ?? null,

                'narrative' => 'Seeking external sell-side liquidity'
            ];
        }

        return [

            'target_side' => 'UNKNOWN',

            'target_price' => null,

            'narrative' => 'No clear liquidity objective'
        ];
    }

    /*
    |--------------------------------------------------------------------------
    | Institutional Narrative
    |--------------------------------------------------------------------------
    */

    public static function buildNarrative(
        string $bias,
        string $location,
        bool $aligned
    ): string {

        if ($aligned) {

            if (
                $bias === 'BUY' &&
                in_array($location, [
                    'DISCOUNT',
                    'EXTREME DISCOUNT'
                ])
            ) {

                return 'Bullish continuation from institutional discount pricing.';
            }

            if (
                $bias === 'SELL' &&
                in_array($location, [
                    'PREMIUM',
                    'EXTREME PREMIUM'
                ])
            ) {

                return 'Bearish continuation from institutional premium pricing.';
            }
        }

        if (!$aligned) {
            return 'Counter-trend positioning against higher timeframe narrative.';
        }

        return 'Market remains inside equilibrium conditions.';
    }

    /*
    |--------------------------------------------------------------------------
    | Institutional Array Score
    |--------------------------------------------------------------------------
    */

    public static function getArrayScore(
        string $bias,
        string $location
    ): int {

        $score = 0;

        if (
            $bias === 'BUY' &&
            $location === 'EXTREME DISCOUNT'
        ) {
            $score = 4;
        }

        elseif (
            $bias === 'BUY' &&
            $location === 'DISCOUNT'
        ) {
            $score = 3;
        }

        elseif (
            $bias === 'SELL' &&
            $location === 'EXTREME PREMIUM'
        ) {
            $score = 4;
        }

        elseif (
            $bias === 'SELL' &&
            $location === 'PREMIUM'
        ) {
            $score = 3;
        }

        elseif ($location === 'EQUILIBRIUM') {
            $score = 1;
        }

        return $score;
    }

    /*
    |--------------------------------------------------------------------------
    | Empty Range
    |--------------------------------------------------------------------------
    */

    private static function emptyRange(): array
    {
        return [

            'range_high' => null,

            'range_low' => null,

            'equilibrium' => null,

            'premium_zone' => [],

            'discount_zone' => [],

            'range_size' => 0
        ];
    }
} 