#!/usr/bin/env python3
"""
照片评分建议生成器
为照片评分结果提供具体的改进建议
"""

class PhotoAdviceGenerator:
    """照片建议生成器类"""
    
    def __init__(self):
        self.quality_advice_db = self._init_quality_advice()
        self.aesthetic_advice_db = self._init_aesthetic_advice()
        self.technical_advice_db = self._init_technical_advice()
    
    def _init_quality_advice(self):
        """初始化质量改进建议数据库"""
        return {
            'clarity': {
                'low': [
                    "使用三脚架或稳定设备减少抖动",
                    "提高快门速度避免运动模糊",
                    "使用自动对焦确保主体清晰",
                    "清洁镜头避免污渍影响",
                    "在光线充足的环境下拍摄"
                ],
                'medium': [
                    "微调对焦点确保主体清晰",
                    "使用更高的分辨率设置",
                    "避免过度压缩图像",
                    "后期适当锐化处理"
                ],
                'high': [
                    "清晰度优秀，继续保持",
                    "可尝试更高难度的拍摄场景"
                ]
            },
            'brightness': {
                'low': [
                    "增加曝光补偿",
                    "使用闪光灯或补光设备",
                    "选择光线更好的拍摄时间",
                    "提高ISO感光度（注意噪点）",
                    "使用反光板补光"
                ],
                'medium': [
                    "微调曝光参数",
                    "使用HDR模式拍摄",
                    "注意高光和阴影的平衡",
                    "后期调整亮度曲线"
                ],
                'high': [
                    "亮度适中，曝光准确",
                    "可尝试创意光影效果"
                ]
            },
            'contrast': {
                'low': [
                    "增加画面明暗对比",
                    "选择色彩对比强烈的场景",
                    "使用侧光或逆光增强立体感",
                    "后期调整对比度参数"
                ],
                'medium': [
                    "适当增强局部对比",
                    "注意高光不过曝，阴影不死黑",
                    "使用曲线工具精细调整"
                ],
                'high': [
                    "对比度良好，层次分明",
                    "可尝试高对比风格创作"
                ]
            },
            'color_balance': {
                'low': [
                    "校正白平衡设置",
                    "使用灰卡进行色彩校准",
                    "避免混合光源造成的色偏",
                    "后期校正色彩平衡"
                ],
                'medium': [
                    "微调色温和色调",
                    "注意肤色还原自然",
                    "统一画面色彩风格"
                ],
                'high': [
                    "色彩平衡优秀，还原准确",
                    "可尝试创意色彩风格"
                ]
            }
        }
    
    def _init_aesthetic_advice(self):
        """初始化美学改进建议数据库"""
        return {
            'composition': {
                'basic': [
                    "学习三分法则构图",
                    "注意主体在画面中的位置",
                    "避免主体过于居中",
                    "利用引导线增强画面深度"
                ],
                'intermediate': [
                    "尝试对称或不对称构图",
                    "利用前景增强层次感",
                    "注意画面元素的平衡",
                    "创造视觉焦点"
                ],
                'advanced': [
                    "构图优秀，可尝试更复杂构图",
                    "探索极简或复杂构图风格",
                    "注重画面节奏和韵律"
                ]
            },
            'lighting': {
                'basic': [
                    "选择黄金时刻拍摄（日出日落）",
                    "避免正午强光直射",
                    "学习使用自然光",
                    "注意光影方向和质量"
                ],
                'intermediate': [
                    "尝试侧光或逆光效果",
                    "利用阴影创造氛围",
                    "控制光比避免过曝或欠曝",
                    "学习使用人造光源"
                ],
                'advanced': [
                    "光线运用娴熟，可尝试创意用光",
                    "探索特殊光线条件拍摄",
                    "注重光影的情感表达"
                ]
            },
            'subject': {
                'basic': [
                    "明确拍摄主体",
                    "简化背景突出主体",
                    "注意主体与环境的互动",
                    "选择有故事性的主体"
                ],
                'intermediate': [
                    "注重主体的表情和姿态",
                    "创造主体与环境的关系",
                    "捕捉决定性瞬间",
                    "注重主体的个性表达"
                ],
                'advanced': [
                    "主体表现力强，可尝试更深层次表达",
                    "探索抽象或概念性主体",
                    "注重主体的象征意义"
                ]
            }
        }
    
    def _init_technical_advice(self):
        """初始化技术改进建议数据库"""
        return {
            'camera_settings': [
                "学习曝光三角关系（光圈、快门、ISO）",
                "根据场景选择合适的拍摄模式",
                "掌握对焦技巧确保主体清晰",
                "合理使用白平衡设置"
            ],
            'post_processing': [
                "学习基本的后期调整技巧",
                "掌握色彩校正和调整",
                "学习锐化和降噪处理",
                "尝试创意滤镜效果"
            ],
            'equipment': [
                "根据需求选择合适的镜头",
                "考虑使用三脚架提高稳定性",
                "投资质量好的存储设备",
                "定期清洁和维护设备"
            ],
            'shooting_techniques': [
                "练习稳定的持机姿势",
                "学习不同的拍摄角度",
                "掌握连拍和定时拍摄",
                "尝试慢门或高速摄影"
            ]
        }
    
    def generate_quality_advice(self, quality_scores):
        """生成质量改进建议"""
        advice = {
            'overall': [],
            'specific': {},
            'priority': []
        }
        
        # 总体建议
        overall_score = sum(quality_scores.values()) / len(quality_scores)
        
        if overall_score >= 90:
            advice['overall'].append("照片质量优秀，继续保持高水平拍摄")
        elif overall_score >= 80:
            advice['overall'].append("照片质量良好，有进一步提升空间")
        elif overall_score >= 60:
            advice['overall'].append("照片质量一般，需要重点改进")
        else:
            advice['overall'].append("照片质量较差，建议系统学习摄影基础")
        
        # 具体维度建议
        for dimension, score in quality_scores.items():
            if dimension in self.quality_advice_db:
                level = self._get_score_level(score)
                dimension_advice = self.quality_advice_db[dimension].get(level, [])
                advice['specific'][dimension] = dimension_advice
                
                # 添加优先级建议
                if score < 70:
                    advice['priority'].append(f"优先改进{dimension}（当前{score}分）")
        
        return advice
    
    def generate_aesthetic_advice(self, aesthetic_score, composition_analysis):
        """生成美学改进建议"""
        advice = {
            'general': [],
            'composition': [],
            'lighting': [],
            'subject': [],
            'creative': []
        }
        
        # 总体美学建议
        if aesthetic_score >= 90:
            advice['general'].append("美学表现优秀，具备专业水准")
            advice['creative'].append("可尝试更具挑战性的创意拍摄")
        elif aesthetic_score >= 80:
            advice['general'].append("美学表现良好，细节有待提升")
            advice['creative'].append("尝试不同的构图和用光方式")
        elif aesthetic_score >= 60:
            advice['general'].append("美学表现一般，需要系统学习")
            advice['creative'].append("从基础构图和用光开始练习")
        else:
            advice['general'].append("美学表现较差，建议学习摄影美学基础")
        
        # 构图建议
        comp_level = self._get_aesthetic_level(aesthetic_score)
        advice['composition'] = self.aesthetic_advice_db['composition'].get(comp_level, [])
        
        # 用光建议
        light_level = self._get_aesthetic_level(aesthetic_score)
        advice['lighting'] = self.aesthetic_advice_db['lighting'].get(light_level, [])
        
        # 主体建议
        subject_level = self._get_aesthetic_level(aesthetic_score)
        advice['subject'] = self.aesthetic_advice_db['subject'].get(subject_level, [])
        
        return advice
    
    def generate_technical_advice(self, photo_type='general'):
        """生成技术改进建议"""
        advice = {
            'camera_settings': self.technical_advice_db['camera_settings'],
            'post_processing': self.technical_advice_db['post_processing'],
            'equipment': self.technical_advice_db['equipment'],
            'shooting_techniques': self.technical_advice_db['shooting_techniques']
        }
        
        # 根据照片类型调整建议
        if photo_type == 'portrait':
            advice['camera_settings'].extend([
                "使用大光圈虚化背景",
                "注意对焦在眼睛上",
                "使用柔光设备美化肤色"
            ])
        elif photo_type == 'landscape':
            advice['camera_settings'].extend([
                "使用小光圈获得大景深",
                "使用三脚架确保稳定性",
                "利用滤镜控制光线"
            ])
        elif photo_type == 'macro':
            advice['camera_settings'].extend([
                "使用微距镜头或近摄环",
                "注意景深控制",
                "使用环形闪光灯补光"
            ])
        
        return advice
    
    def generate_personalized_advice(self, quality_scores, aesthetic_score, photo_content):
        """生成个性化综合建议"""
        personalized = {
            'quick_wins': [],
            'long_term_improvements': [],
            'learning_resources': [],
            'practice_exercises': []
        }
        
        # 快速改进建议
        low_score_dimensions = [dim for dim, score in quality_scores.items() if score < 70]
        if low_score_dimensions:
            personalized['quick_wins'].append(f"重点改进：{', '.join(low_score_dimensions)}")
        
        # 长期改进建议
        if aesthetic_score < 80:
            personalized['long_term_improvements'].append("系统学习摄影构图和用光")
        
        # 学习资源推荐
        personalized['learning_resources'].extend([
            "推荐书籍：《摄影构图学》、《美国纽约摄影学院教材》",
            "在线课程：B站摄影教程、摄影之友",
            "实践平台：参加摄影比赛、加入摄影社群"
        ])
        
        # 练习建议
        personalized['practice_exercises'].extend([
            "每日拍摄练习：同一主题不同角度",
            "技术练习：曝光、对焦、白平衡",
            "创意练习：尝试不同风格和主题"
        ])
        
        return personalized
    
    def _get_score_level(self, score):
        """根据分数获取等级"""
        if score >= 85:
            return 'high'
        elif score >= 70:
            return 'medium'
        else:
            return 'low'
    
    def _get_aesthetic_level(self, score):
        """根据美学分数获取等级"""
        if score >= 85:
            return 'advanced'
        elif score >= 70:
            return 'intermediate'
        else:
            return 'basic'

def get_quality_improvement_advice(quality_scores):
    """获取质量改进建议"""
    try:
        advisor = PhotoAdviceGenerator()
        return advisor.generate_quality_advice(quality_scores)
    except Exception as e:
        return {'error': f"生成建议失败: {str(e)}"}

def get_aesthetic_improvement_advice(aesthetic_score, composition_analysis=None):
    """获取美学改进建议"""
    try:
        advisor = PhotoAdviceGenerator()
        return advisor.generate_aesthetic_advice(aesthetic_score, composition_analysis)
    except Exception as e:
        return {'error': f"生成建议失败: {str(e)}"}

def get_technical_advice(photo_type='general'):
    """获取技术改进建议"""
    try:
        advisor = PhotoAdviceGenerator()
        return advisor.generate_technical_advice(photo_type)
    except Exception as e:
        return {'error': f"生成建议失败: {str(e)}"}

def get_personalized_advice(quality_scores, aesthetic_score, photo_content):
    """获取个性化综合建议"""
    try:
        advisor = PhotoAdviceGenerator()
        return advisor.generate_personalized_advice(quality_scores, aesthetic_score, photo_content)
    except Exception as e:
        return {'error': f"生成建议失败: {str(e)}"}