from rest_framework import serializers

from .models import BenchmarkPrice, CashFlow, Portfolio, PortfolioSnapshot, Stock, Transaction


class StockSerializer(serializers.ModelSerializer):
    class Meta:
        model = Stock
        fields = ['id', 'portfolio', 'stock_code', 'quantity']
        read_only_fields = ['id']


class TransactionSerializer(serializers.ModelSerializer):
    action_display = serializers.CharField(source='get_action_display', read_only=True)

    class Meta:
        model = Transaction
        fields = [
            'id',
            'portfolio',
            'action',
            'action_display',
            'stock_code',
            'quantity',
            'price_per_share',
            'currency',
            'fee',
            'broker_trade_id',
            'source',
            'confidence',
            'date',
            'created_at',
        ]
        read_only_fields = ['id', 'created_at']
        extra_kwargs = {
            'price_per_share': {'required': False, 'allow_null': True},
            'fee': {'required': False, 'allow_null': True},
            'currency': {'required': False},
            'broker_trade_id': {'required': False, 'allow_blank': True},
            'source': {'required': False, 'allow_blank': True},
            'confidence': {'required': False, 'allow_null': True},
        }


class CashFlowSerializer(serializers.ModelSerializer):
    flow_type_display = serializers.CharField(source='get_flow_type_display', read_only=True)
    signed_amount = serializers.DecimalField(max_digits=20, decimal_places=2, read_only=True)
    external_signed_amount = serializers.DecimalField(max_digits=20, decimal_places=2, read_only=True)
    is_external = serializers.BooleanField(read_only=True)

    class Meta:
        model = CashFlow
        fields = [
            'id',
            'portfolio',
            'flow_type',
            'flow_type_display',
            'amount',
            'signed_amount',
            'external_signed_amount',
            'is_external',
            'currency',
            'date',
            'source',
            'note',
            'confidence',
            'created_at',
        ]
        read_only_fields = ['id', 'created_at']
        extra_kwargs = {
            'currency': {'required': False},
            'source': {'required': False, 'allow_blank': True},
            'note': {'required': False, 'allow_blank': True},
            'confidence': {'required': False, 'allow_null': True},
        }


class PortfolioSnapshotSerializer(serializers.ModelSerializer):
    portfolio_name = serializers.CharField(source='portfolio.name', read_only=True)

    class Meta:
        model = PortfolioSnapshot
        fields = ['id', 'portfolio', 'portfolio_name', 'captured_at', 'total_value']
        read_only_fields = ['id']


class BenchmarkPriceSerializer(serializers.ModelSerializer):
    class Meta:
        model = BenchmarkPrice
        fields = ['id', 'ticker', 'date', 'close']
        read_only_fields = ['id']


class PortfolioSerializer(serializers.ModelSerializer):
    stocks = StockSerializer(many=True, read_only=True)

    class Meta:
        model = Portfolio
        fields = ['id', 'name', 'created_at', 'stocks']
        read_only_fields = ['id', 'created_at']


class PortfolioListSerializer(serializers.ModelSerializer):
    stock_count = serializers.SerializerMethodField()

    class Meta:
        model = Portfolio
        fields = ['id', 'name', 'created_at', 'stock_count']
        read_only_fields = ['id', 'created_at']

    def get_stock_count(self, obj):
        return obj.stocks.count()


class AIHoldingInputSerializer(serializers.Serializer):
    stock_code = serializers.CharField()
    quantity = serializers.FloatField()


class AIUpdateSerializer(serializers.Serializer):
    portfolio_id = serializers.IntegerField()
    holdings = AIHoldingInputSerializer(many=True)
    reset = serializers.BooleanField(default=False)


class HoldingSerializer(serializers.Serializer):
    stock_code = serializers.CharField()
    quantity = serializers.FloatField()
    current_price = serializers.FloatField()
    current_value = serializers.FloatField()
    ref_price = serializers.FloatField(required=False, allow_null=True)
    price_change = serializers.FloatField(required=False, allow_null=True)
    price_change_pct = serializers.FloatField(required=False, allow_null=True)
    value_change = serializers.FloatField(required=False, allow_null=True)


class PortfolioHoldingsSerializer(serializers.Serializer):
    portfolio_id = serializers.IntegerField()
    portfolio_name = serializers.CharField()
    holdings = HoldingSerializer(many=True)
    total_value = serializers.FloatField()


class AIUpdateResultSerializer(serializers.Serializer):
    stock_code = serializers.CharField()
    quantity = serializers.FloatField()
    created = serializers.BooleanField()
