package com.vetti.web.controller.ai;

import com.vetti.common.ai.elevenLabs.ElevenLabsClient;
import com.vetti.common.ai.gpt.ChatGPTClient;
import com.vetti.common.ai.gpt.OpenAiStreamClient;
import com.vetti.common.ai.gpt.service.OpenAiStreamListenerService;
import com.vetti.common.ai.whisper.WhisperClient;
import com.vetti.common.core.controller.BaseController;
import com.vetti.common.core.domain.AjaxResult;
import com.vetti.common.core.domain.R;
import com.vetti.common.core.domain.dto.RealtimeClientSecretDto;
import com.vetti.web.service.ICommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * AI 共通测试接口处理
 *
 * @author wangxiangshun
 */
@Api(tags ="AI 共通测试接口处理")
@RestController
@RequestMapping("/aiCommon")
public class AiCommonController extends BaseController
{
    @Autowired
    private ElevenLabsClient elevenLabsClient;

    @Autowired
    private ChatGPTClient chatGPTClient;

    @Autowired
    private WhisperClient whisperClient;

    @Autowired
    private OpenAiStreamClient streamClient;

    @Autowired
    private ICommonService commonService;

    /**
     * 进行文本转语音处理
     */
    @ApiOperation("进行文本转语音处理")
    @GetMapping("/handleTextToVice")
    public AjaxResult handleTextToVice()
    {
        //你好,我是本次的面试官Vetti,请点击开始按钮后,做一段自我介绍.
        //你好,我是本次的面试官Vetti,请在三秒后,开始做一段自我介绍.
        //本轮面试结束,谢谢您的配合,面试结果将稍后通知

//        elevenLabsClient.handleTextToVoice("I usually get started and will stop only if a hazard becomes a problem.","/Users/wangxiangshun/Desktop/临时文件/Low-1.wav");
//
//        elevenLabsClient.handleTextToVoice("I use whatever is available and make do if something is missing.","/Users/wangxiangshun/Desktop/临时文件/Low-2.wav");
//
//        elevenLabsClient.handleTextToVoice("If the supervisor sees an issue, I'll fix it then.","/Users/wangxiangshun/Desktop/临时文件/Low-3.wav");
//
//        elevenLabsClient.handleTextToVoice("I keep to myself unless there's a major problem.","/Users/wangxiangshun/Desktop/临时文件/Low-4.wav");
//
//        elevenLabsClient.handleTextToVoice("I start with what's available and figure out the rest as I go.","/Users/wangxiangshun/Desktop/临时文件/Low-5.wav");
//
//        elevenLabsClient.handleTextToVoice("I ignore it unless it directly stops my work.","/Users/wangxiangshun/Desktop/临时文件/Low-6.wav");
        return success();
    }

    /**
     * AI 聊天
     */
    @ApiOperation("AI 聊天")
    @GetMapping("/handleAiChat")
    public AjaxResult handleAiChat(@RequestParam String text)
    {
        String pom = "[\n" +
                "    {\n" +
                "        \"role\": \"user\",\n" +
                "        \"content\": \"从下面提供的文本中提取所有能识别到的简历信息，只提取原文中存在的内容，不要补充、不推测、不总结。需要提取的字段包括：name（姓名）、phone（电话号码）、email（电子邮件地址）、links（所有链接地址）、about（关于我/自我介绍）、skills_tools（关键资格（许可证、注册/会员资格、认证））、languages（语言能力）、experience（工作经历(除了title、company、location、duration其他的都放到描述里面)）、education（教育经历）。请将提取结果以结构化 JSON 格式返回，格式如下：{ \\\"name\\\": \\\"\\\", \\\"phone\\\": \\\"\\\", \\\"email\\\": \\\"\\\", \\\"links\\\": [{\\\"content\\\":\\\"\\\"}], \\\"about\\\": \\\"\\\", \\\"skillsTools\\\": [{\\\"content\\\":\\\"\\\"}], \\\"languages\\\": [{\\\"content\\\":\\\"\\\"}], \\\"experience\\\": [{\\\"title\\\": \\\"\\\", \\\"company\\\": \\\"\\\",\\\"location\\\": \\\"\\\",\\\"duration\\\": \\\"\\\",\\\"description\\\": [{\\\"content\\\":\\\"\\\"}]}], \\\"education\\\": [{\\\"degree\\\": \\\"\\\",\\\"institution\\\": \\\"\\\",\\\"date\\\": \\\"\\\"}] }。字段不存在则返回 null 或空数组。只返回标准可解析的 JSON结构 ,不要多余的```json等信息，不要解释说明，不要改写内容。以下为待处理文本： Page | 1  \\nFred Nouri Curriculum Vitae \\nEmail: nouri.lgi@gmail.com              M: 0401 084 098 \\nPROJECT EXPERIENCE \\nDec 2023 – June 2025 | Hill International Inc. Saudi Arabia | Construction Business Unit Projects Manager \\nProject: Portfolio of 129 active construction projects across the Southern Cluster in Saudi Arabia, including \\nwater and wastewater infrastructure. Key projects include regional pipeline networks, water reservoir \\nexpansions, pumping stations, treatment plant upgrades, and utility relocations. Major initiatives encompass \\nAsir, Jazan, Al Baha, and Najran regions, collectively valued at over $30B. \\n \\nCompany’s role in the Project: PMO / PMC | Value: USD 30+b \\nResponsibilities: \\n\uF0FC Leadership & Strategic Oversight: Managed a portfolio of 129 active construction projects across the Southern \\nCluster, including Asir, Jazan, Al Baha, and Najran in the Kingdom of Saudi Arabia, leading a team of 22 Program \\nManagers, Project Managers and Project engineers. Providing visionary leadership to ensure alignment with \\nstrategic business objectives and achieving successful delivery. \\n\uF0FC Strategic Project Leadership: Managed high-profile infrastructure and utilities programs, providing leadership \\nfrom initial planning through successful completion, ensuring projects adhered to budgetary and scheduling \\nconstraints. Guided design, coordination, and construction phases, driving project success through effective \\ndecision-making and strategic oversight. \\n\uF0FC Client & Stakeholder Engagement: Acted as the primary representative for the organization with clients and \\nsuppliers, securing client objectives and negotiating scope changes. Led client-facing presentations and ensured \\nproject alignment with client vision and requirements. \\n\uF0FC Infrastructure Design & Technical Excellence: Oversaw infrastructure design development and technical \\nquality, managing a team of technical specialists and ensuring strict compliance with quality standards and \\nproject objectives. \\n\uF0FC Project Value Improvement (PVI) Implementation: Spearheaded the Project Value Improvement (PVI) initiative, \\nintegrating lessons learned and advanced technology to optimize project delivery in both design and \\nconstruction, minimizing errors and enhancing project value. \\n\uF0FC Regulatory Compliance and Risk Management: Ensured full adherence to legal and regulatory standards across \\nall projects, securing necessary permits, maintaining compliance with health and safety, and quality assurance \\nprotocols. \\n\uF0FC Budget & Schedule Management: Established and maintained project scopes, schedules, and budgets, \\nimplementing cost control measures and providing transparent progress updates to senior management. \\n\uF0FC Resource Allocation & Team Development: Mobilized and assigned project resources effectively, leveraging \\nteam strengths to drive project execution. Provided input on performance reviews, supporting team \\ndevelopment and growth. \\n\uF0FC Financial and Programmatic Oversight: Managed project budgets with expertise in cost accounting, ensuring \\nfinancial performance aligned with objectives and reporting on key financial metrics. \\n\uF0FC Cross-Functional Collaboration and Comprehensive Planning: Worked seamlessly with consultants, contractors, \\nand subcontractors to maintain project momentum, drive efficiency, and address potential delays or scope \\nchanges. \\n\uF0FC Project Controls & Governance Excellence: Established and implemented robust project control frameworks to \\nmonitor progress, ensure alignment with contractual and strategic goals, and enforce governance standards \\nthroughout the project lifecycle. Exercised rigorous oversight of project performance indicators, driving \\naccountability and operational transparency via structured control systems. \\n\uF0FC Integrated Planning & Program Governance: Developed comprehensive master schedules and aligned planning \\nmethodologies with organizational objectives. Oversaw governance frameworks ensuring compliance with \\ncorporate protocols, regulatory mandates, and contractual requirements, thereby enhancing project visibility and \\nenabling informed decision-making across all phases. \\n\uF0FC Milestone-Driven Management and Operational Efficiency: Maintained a focus on key milestones to ensure \\nproject completion within scope, budget, and time constraints, driving operational efficiency and successful \\nproject outcomes. \\n \\nMay 2021 – Sep 2023 | Sydney Water Corporation Sydney, Australia | Project Manager \\n \\nProjects: Upper South Creek Networks Program for Water and Wastewater pipelines and pumping stations, \\nWastewater Treatment Plant’s. Development of Business Cases from Needs to Delivery including Concept Design \\nand delivery design, Western Sydney Aerotropolis Upper South Creek: $2.1B+ AWRC & Network Project, USCN \\nAdvance Water Recycling Plant: $1.6B, Western Sydney Water and Wastewater Pipelines, Manholes, Pumping \\nStations: $2.0B, Sydney Austral/Leppington Greenfield Program: $394M, Sydney Richmond WRP/North \\nRichmond WWTP Precinct Upgrade Project: $155.9M, Sydney Rosehill Wastewater Treatment Plant & WRP. \\nPage | 2  \\n \\nCompany’s role in the Project: Client of the Project | Value: AUD 30B over 10 Years \\nResponsibilities: \\n\uF0FC Project Management for Austral-Leppington Greenfield site 5-year program to meet state government housing \\ngoals managing West Sydney Delivery Team Contractor from concept to detailed design & Delivery \\n\uF0FC Advanced Business Cases Development: Developed Need Approval, Option Approval, Delivery Approval and \\nVariation Approval Business Cases for Projects including Risk Based Cost Estimates Workshops,  \\n\uF0FC Conducting Workshops: Project Risk Workshops, Environmental Risks Workshop and Wastewater Treatment \\nPlants Decommissioning Workshops \\n\uF0FC Contractual and Program Management Excellence: Managing of the NEC 4 Contract with West Region Delivery \\nTeam i.e. Fulton Hogan, Abergeldie and SWC project management team and managed delivery main and sub-\\ncontractors according to NEC4 contract \\n\uF0FC Managing RFIs, Early Warnings, Compensation Events, Works Requests, Work to proceed via SW delivery \\nPortal \\n\uF0FC Comprehensive SAP/Bxp Oversight: SAP/Bxp management such as Resource assignment, PR/PO processes, \\nP44 cost planning, EPPM Project suits, Managed purchase orders from requisition to service and/or good \\nreceipt & payment \\n\uF0FC Modification of Richmond Waste Treatment plant to meet EPA compliance and growth \\n\uF0FC Facilitating risk-based solutions as part of value engineering to meet program outcomes and goals \\n\uF0FC Financial and Programmatic Oversight: Overseeing Financial & Commercial programs and plans TOC inclusive \\n\uF0FC Managing issues & risks on program, contractor performance, planning, engineering & commercial \\n\uF0FC Sophisticated Design and Project Delivery: Managed 50%-90% Designs Drawings development and CHAIR \\nmeetings and Managed IFC drawings development & supply chain negotiations according to design \\n\uF0FC Milestone-Driven Management and Operational Efficiency: Optimized project schedules and operational \\nworkflows to ensure timely, efficient project delivery. \\n\uF0FC Power BI for Data Visualization & Reporting: Used Power BI to create dynamic dashboards and real-time \\nreports, integrating data from multiple project management platforms. Enhanced decision-making capabilities \\nfor senior management through clear, interactive visualizations that track project performance, risks, and key \\nmetrics. \\n\uF0FC Strategic Decision-Making and Stakeholder Engagement: Engaged stakeholders with data-driven insights to \\ninform high-impact decisions and enhance project support. \\n \\nAchievements: \\n\uF0FC Developed the Greenfield Program for Western Greater Sydney Upper South Creek, valued at $1.6B AWRC & \\nNetwork. \\n\uF0FC Established the Greenfield Program for the South-West Region Aerotropolis Areas of Austral Leppington linked to \\nthe New South-West Airport, valued at $2.0B. \\n\uF0FC Developed the program for the modification and amplification of Richmond’s Pump Stations and Treatment Plant, \\nincluding decommissioning redundant assets. \\n\uF0FC Successfully delivered the Austral/Leppington Water and Wastewater Pipeline and Pumping Station Project, valued \\nat $394M. \\n\uF0FC Developed and implemented risk-based budgets for both programs, facilitating property acquisitions and \\ncompliance with environmental regulations within approved Review of Environmental Factors (REF). \\n\uF0FC Developed Needs, Option, and Delivery Approval Business Cases for the Ministry of Water and Energy. \\n\uF0FC Formulated Strategy and Final Business Cases for Infrastructure New South Wales State Government Gateways. \\n \\nOct 2018 – May 2021 | MU Group Infrastructure Consulting Sydney, Australia | Project Manager  \\nProjects: West Connex, a 33km pipeline of motorways and tunnels located in southeast of Sydney Greater Area, \\nGreat Western Highway Design and New build, Acciona/Samsung/Bouygues Joint Venture (ASB JV) For West \\nConnex (M4-M5 Link) St Peters and Rozelle Interexchange Tunnels $16.8 Billion Tunneling and Motorways \\nProject, Bridges Design and Rehabilitation $389M, 60+ Condition Assessment of Traffic Lights, Roads, Bridges \\nand Pavement, Housing development site design development for 600+ Units \\nCompany’s role in the Project: Design and Project Management Consultant Value: USD 12b  \\n \\nResponsibilities: \\n\uF0FC Project Development & Delivery: Directed the design, rehabilitation, and construction phases for RMS Regional \\nMaintenance Delivery (RMD) projects, ensuring quality outcomes aligned with project specifications. \\n\uF0FC Capital Works Planning & Coordination: Led capital works planning and project coordination, aligning resources \\nto meet strategic objectives and timelines. \\n\uF0FC Condition Assessment & Reporting: Conducted in-depth condition assessments, producing actionable reports \\nthat guided project planning and prioritization. \\n\uF0FC Structural Issue Identification: Identified and assessed structural issues, ensuring early detection and resolution \\nfor project stability and safety. \\n\uF0FC Site Engineering & Civil Supervision: Provided on-site engineering oversight, coordinating civil supervision to \\nuphold technical standards and project integrity. \\nPage | 3  \\n\uF0FC Preliminary Work Planning: Managed initial project planning stages, establishing foundational frameworks for \\nsmooth execution. \\n\uF0FC SAP for Financial Tracking & Resource Management: Utilized SAP software to manage project budgets, track \\nexpenditures, and allocate resources efficiently. Provided accurate financial reporting and forecasting, \\nsupporting cost control measures and ensuring fiscal accountability aligned with project and organizational \\nobjectives. \\n\uF0FC Tender & Project Document Management: Oversaw tender processes and maintained meticulous control of \\nproject documents to support compliance and transparency. \\n\uF0FC Financial Management: Administered budgets and financial tracking, ensuring cost-effective project execution. \\n\uF0FC Variation Management & Negotiation: Managed variations and led negotiations to maintain budgetary \\nalignment while accommodating project changes. \\n\uF0FC Schedule Risk Management & Mitigation: Directed proactive identification, analysis, and mitigation of \\nschedule-related risks, employing quantitative and qualitative techniques to forecast potential delays \\nand develop contingency plans. Maintained schedule integrity through continuous risk assessments \\nand scenario planning, ensuring resilience against disruptions and safeguarding critical milestones. \\nAchievements: \\n\uF0FC West Connex: Completion of Civil Works, Service Installation, Drainages, Pressure Tests and Cross Passages \\n\uF0FC Made Sure FY 19/20 Quarter 3- And 4 Pavement and Major Civil Projects Completed According to The Program. \\n\uF0FC Creation Of Sophisticated Gantt Chart Program For $70M FY 20/21- Works, Major Civil and Pavement Projects \\n\uF0FC Overall Saving Of $6.5M Within $150M Budget for Panel Pavement Program in FY19-20 Q3&4 \\nOct 2016 – Sep 2018 | Canterbury & Bankstown City Council \\nSydney | Project & Program Manager for Roads Operations & Capital Works \\nProjects: Capital Works such as Roads, bridges resurfacing and asphalt \\nCompany’s role in the Project: Client of the project | Value: AUD 500k-50M \\nResponsibilities: \\n\uF0FC Project Coordination: Coordinated assigned capital works, including asphalt and associated civil works projects, \\nfrom initial planning through to completion. Ensured that all project phases were executed efficiently and \\neffectively. Managed Sydney Road and Assets Performance Contract. \\n\uF0FC Stakeholder Engagement, Community Communication, Contractual Documentation, Compliance Oversight, \\nTechnical & Project Management, Quality, WHS & Environmental Compliance, Stakeholder Representation, Project \\nMeetings, Financial Management, Variation Management, Procurement & Scheduling, Risk Management, Team \\nLeadership \\nAchievements: \\n\uF0FC Made Sure Pavement and Major Civil Projects Completed According to The Program \\n\uF0FC Creation Sophisticated Gantt Chart Program For $170M - Works, Major Civil and Pavement Projects \\n\uF0FC Overall Saving Of $6.8m Within $150M Budget for Panel Pavement Program \\n \\nNov 2013 – Oct 2016 | Downer EDI | Sydney, Australia | Project Manager \\nProjects: Road and Motorways New builds and widening projects, Slope remediation, Storm Water new builds, \\nGreater Sydney Area Asset Performance contract management, Motorways New Builds. \\nCompany’s role in the Project: Delivery Contractor and Designer | Value: AUD 2M-100M \\nResponsibilities: \\n\uF0FC Contract Documentation Assessment: Evaluated comprehensive contract documentation, including Project \\nManagement Plans (PMP), Zero Harm Management Plans (ZHMP), Construction Environmental Management Plans \\n(CEMP), Quality Management Plans (QMP), Emergency Management Plans (EMP), Safe Work Method Statements \\n(SWMS), Material Safety Data Sheets (MSDS), Approved for Construction Drawings (AFC Drawings), Traffic \\nManagement Plans (TMP), Traffic Control Plans (TCP), and Project Programs. Ensured thorough review and \\ncompliance with project requirements. \\n\uF0FC Project and Construction Management, Project Planning & Forecasting, Profit & Loss Calculation, Quality & Risk \\nControl, Risk Assessment Workshops, Site Management & Permits, Site Inspections & Progress Monitoring, Design \\nCollaboration & RFI Management, Statutory Reporting & Liaison, Utility Coordination, Daily & Weekly Reporting, \\nIssue Resolution & Improvement, Stakeholder Relationship Management, Defect Management \\nAchievements: \\n\uF0FC TfNSW Intersection Upgrade Project Delivered Within Time Frame and Budget With 10% Variations. \\n\uF0FC TfNSW Slope Rehabilitation Projects on M1 Delivered Within Time Frame and Budget / Savings: 6% \\n\uF0FC TfNSW Pavement Projects Delivered on Time and Within the Project Budget. \\n\uF0FC No Service Strikes Within 4 Months in Cumberland Hwy/Merrylands Rd. Due to Permanent Supervision and \\nCollaboration with All Stockholders on Site. \\n \\n \\nPage | 4  \\nApr 2010 – Nov 2013 | VBA JV | Sydney, Australia | Site Supervisor → Senior Project Engineer \\nProjects: Bridge New builds, Intersection Widening, Utilities, Storm Water and Water pipeline projects, Bridge \\nRehabilitations \\nCompany’s role in the Project: Delivery Contractor and Designer for SRAP (Sydney Asset Performance Contract 10 \\nYears Program) | Value: AUD 5M-100M \\nResponsibilities: \\n\uF0FC Project Management: Directed the RMS-Sydney Maintenance Contract, overseeing a range of assets including \\ncorridors, bridges, tunnels, tactical pavements, minor complexes, intersection upgrades, services, utilities, slopes, \\nretaining walls, culverts, new builds, excavation, and demolition works. Managed projects from the tender stage \\nthrough to successful completion. \\n\uF0FC Stakeholder Liaison, Design & Documentation Assessment, Team Management, Variation & Financial \\nManagement, Site & Project Oversight, Compliance & Documentation, Risk Assessment & Permits, Contractor \\nIntegration & Compliance \\nAchievements: \\n\uF0FC Road And Motorways Upgrade, And Pavement Projects Delivered on Time and Within Budget with Savings Up To \\n14% \\n\uF0FC Culverts Rehabilitation and Guard Rail Projects Delivered Within Project Time and Budget Without Variations. \\n\uF0FC No Major Accidents or ZERO Harm Issues on Site \\n \\nMarch 2008 – April 2010 | Kashan Construction | Sydney & ACT |Project Manager \\nProject: Subdivision developments and housing projects, residential and commercial construction \\nCompany’s role in the Project: Delivery Contractor and Designer | Value: AUD 5M-100M \\nResponsibilities: \\n\uF0FC Project Management: Directed the rehabilitation, maintenance, and construction of roads, bridges, and utilities, \\nensuring project delivery from initiation to completion. \\n\uF0FC Commitment Delivery, Program Development and scheduling, Compliance Assurance, Utility Coordination, Risk \\nManagement, Organizational Representation, Reporting, Financial Management \\nAchievements: \\n\uF0FC Up To 15% Savings on Purchasing Equipment’s and Materials. \\n\uF0FC Up To 20% Savings on Services and Ad \\n\uF0FC 5% Project Schedule Time Savings \\n\uF0FC Projects Delivered Within Time Frame and Budget. \\n \\nFeb 2003 – Jan 2008 | HAE Construction | MENA Region | Project Engineer → Project Manager \\nSep 2000 – Jan 2003 | Bau Mitte Demuth GmbH Germany |Junior Project Engineer → Project Engineer \\n \\nEDUCATION \\nB.Sc. Civil Engineering, Berlin, Germany \\nLANGUAGES \\nEnglish, German \\nNationalities: \\nGerman | Australian Permanent Resident \\n  KEY QUALIFICATIONS (LICENSES, REGISTRATIONS/MEMBERSHIPS, CERTIFICATIONS) \\n2025: PMI, PPS (In progress) (United States) \\n2024: Professional Accreditation of bachelor’s degree by Ministry of Human Resource (QVP/KSA) \\n2024 Council of Engineers Membership (KSA) \\n2024: PfMP (United States) \\n2023: Finance for Project Managers, Australian Institute of Management, Sydney, Australia.  \\n2021: PMP (United States) \\n2020: Project Management Essentials, Australian Institute of Management, Sydney, Australia.  \\n2019: Work Safety at Heights, Coates Hire Training Services, Sydney, Australia \\n2018: First Aid, CPR & Basic Life Support, Medi Life Education, Sydney, Australia  \\n2015: Work Safety in The Construction Industry, Eclipse Education, Sydney, Australia  \\n2015: Asbestos Awareness, Keys Human Resources, Sydney, Australia \\n \\n\"\n" +
                "    }\n" +
                "]";


        String resultMsg = chatGPTClient.handleAiChat(pom,"JX");
        return AjaxResult.success(resultMsg);
    }

    /**
     * AI 流式聊天
     */
    @ApiOperation("AI 流式聊天")
    @GetMapping("/stream/handleAiChat")
    public AjaxResult handleAiStreamChat(@RequestParam String text)
    {
        streamClient.streamChat(text, new OpenAiStreamListenerService() {
            @Override
            public void onMessage(String content) {
                System.out.println("AI 返回数据: "+content);
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }
        });


        String resultMsg = chatGPTClient.handleAiChat(text,"QA");
        return AjaxResult.success(resultMsg);
    }



    /**
     * 进行语音转文本处理
     */
    @ApiOperation("进行语音转文本处理")
    @GetMapping("/handleViceToText")
    public AjaxResult handleViceToText()
    {
        whisperClient.handleVoiceToText("F:\\/output.mp3");
        return success();
    }


    /**
     * 获取客户端临时Key
     */
    @ApiOperation("获取客户端临时Key")
    @GetMapping("/getRealtimeClientSecret")
    public R<RealtimeClientSecretDto> handleRealtimeClientSecret()
    {
        RealtimeClientSecretDto dto = commonService.getRealtimeClientSecret();
        return R.ok(dto);
    }

}
