from fastapi import FastAPI
from .data import website_data
from pydantic import BaseModel
from .agent import assistant
from fastapi.middleware.cors import CORSMiddleware
from .utils import load_data, save_data
import importlib.resources
from pathlib import Path
from fastapi.staticfiles import StaticFiles


app = FastAPI(
    title="SoftiqTech Assistant Agent - Sofi",
    description="An AI-powered assistant agent for SoftiqTech's website.",
    version="1.0.0"
)


# def mount_frontend(app: FastAPI, prefix: str = "/sofi"):
#     package_path = Path(importlib.resources.files("softiqtech_sofi_agent")) # type: ignore
#     frontend_path = package_path / "frontend_build"

#     if not frontend_path.exists():
#         raise FileNotFoundError(
#             f"frontend_build folder not found inside package at {frontend_path}"
#         )

#     app.mount(
#         prefix,
#         StaticFiles(directory=str(frontend_path), html=True),
#         name="softiqtech_sofi_frontend"
#     )


def mount_frontend(app: FastAPI, prefix: str = "/sofi"):
    # Locate the package path
    package_path = Path(importlib.resources.files("softiqtech_sofi_agent"))  # type: ignore
    frontend_path = package_path / "frontend_build"

    if not frontend_path.exists():
        raise FileNotFoundError(
            f"frontend_build folder not found inside package at {frontend_path}"
        )

    # Mount the main frontend
    app.mount(
        prefix,
        StaticFiles(directory=str(frontend_path), html=True),
        name="softiqtech_sofi_frontend"
    )

    # Mount the kawaii_cute_flying_robot folder separately
    kawaii_path = frontend_path / "kawaii_cute_flying_robot"
    if not kawaii_path.exists():
        raise FileNotFoundError(
            f"kawaii_cute_flying_robot folder not found inside frontend_build at {kawaii_path}"
        )

    app.mount(
        "/kawaii_cute_flying_robot",
        StaticFiles(directory=str(kawaii_path)),
        name="kawaii_cute_flying_robot"
    )

# Mount frontend
mount_frontend(app, "/sofi")

# Main Route:
@app.get("/")
async def read_root():
    return {"message": "Welcome to the Chat box of SoftiqTech Assistant Agent - Sofi!"}

# Home Page Route:
@app.get("/homepage")
async def get_homepage():
    return website_data["homepage"]

# Home Page Sub-Sections Routes:
@app.get("/homepage/herosection")
async def get_herosection():
    return website_data["homepage"]["hero_section"]

@app.get("/homepage/gettoknowus")
async def get_gettoknowus():
    return website_data["homepage"]["Get_To_Know_SoftiqTech"]

@app.get("/homepage/whatsoffering")
async def get_whatsoffering():
    return website_data["homepage"]["What_SoftiqTech_Offers"]

@app.get("/homepage/projects")
async def get_compprojects():
    return website_data["homepage"]["Completed_Projects"]

@app.get("/homepage/whychooseus")
async def get_whychooseus():
    return website_data["homepage"]["Why_Choose_SoftiqTech"]

@app.get("/homepage/testimonials")
async def get_testimonials():
    return website_data["homepage"]["Client_Testimonials"]

@app.get("/homepage/footer")
async def get_footer():
    return website_data["homepage"]["Footer"]

# About Page Route:
@app.get("/aboutpage")
async def get_aboutpage():
    return website_data["aboutpage"]

# About Page Sub-Section Routes:
@app.get("/aboutpage/companyoverview")
async def get_companyoverview():
    return website_data["aboutpage"]["company_overview"]

@app.get("/aboutpage/mission")
async def get_mission():
    return website_data["aboutpage"]["our_mission"]

@app.get("/aboutpage/vision")
async def get_vision():
    return website_data["aboutpage"]["our_vision"]

@app.get("/aboutpage/values")
async def get_values():
    return website_data["aboutpage"]["our_values"]

@app.get("/aboutpage/members")
async def get_members():
    return website_data["aboutpage"]["meet_the_team"]


# Services Page Route:
@app.get("/servicepage")
async def get_servicepage():
    return website_data["servicespage"]

# Services Page Sub-Section Routes:
@app.get("/servicepage/services")
async def get_servicelist():
    return website_data["servicespage"]["services"]

@app.get("/servicepage/services/webdevelopment")
async def get_service1():
    return website_data["servicespage"]["services"]["Web_Developement"]

@app.get("/servicepage/services/appdevelopment")
async def get_service2():
    return website_data["servicespage"]["services"]["App_Developement"]

@app.get("/servicepage/services/uiuxdesigning")
async def get_service3():
    return website_data["servicespage"]["services"]["UI/UX_Designing"]

@app.get("/servicepage/services/aichatbots")
async def get_service4():
    return website_data["servicespage"]["services"]["AI_Agents_&_Chatbots"]

@app.get("/servicepage/services/digitalmarketing")
async def get_service5():
    return website_data["servicespage"]["services"]["Digital_Marketing"]

@app.get("/servicepage/services/graphicsdesigning")
async def get_service6():
    return website_data["servicespage"]["services"]["Graphics_Designing"]

# Project Page Route:
@app.get("/projectspage")
async def get_projectspage():
    return website_data["projectspage"]

# Project Page Sub-Section Routes:
@app.get("/projectspage/projects")
async def get_projects():
    return website_data["projectspage"]["projects"]


# Dynamic Completed Projects Route:
# Model for adding a new project
class Comp_Project(BaseModel):
    title: str
    description: str

class Ongoing_Project(BaseModel):
    title: str
    description : str

class Upcoming_Project(BaseModel):
    title: str
    description : str

@app.get("/projectspage/completedprojects")
async def get_completed_projects():
    data = load_data()
    return data["completed_projects"]

@app.post("/projectspage/completedprojects/add")
async def add_completed_project(project: Comp_Project):
    data = load_data()

    # Create unique ID
    new_id = f"proj_{len(data['completed_projects']) + 1}"

    data["completed_projects"][new_id] = {
        "title": project.title,
        "description": project.description
    }

    save_data(data)

    return {"status": "success", "project_id": new_id}


@app.delete("/projectspage/completedprojects/{project_id}")
async def delete_completed_project(project_id: str):
    data = load_data()

    if project_id not in data["completed_projects"]:
        return {"status": "error", "message": "Project not found"}

    del data["completed_projects"][project_id]
    save_data(data)

    return {"status": "deleted", "project_id": project_id}


@app.get("/projectspage/ongoingprojects")
async def get_ongoing_projects():
    data = load_data()
    return data["ongoing_projects"]

@app.post("/projectspage/ongoingprojects/add")
async def add_ongoing_project(project: Ongoing_Project):
    data = load_data()

    # Create unique ID
    new_id = f"proj_{len(data['ongoing_projects']) + 1}"

    data["ongoing_projects"][new_id] = {
        "title": project.title,
        "description": project.description
    }

    save_data(data)

    return {"status": "success", "project_id": new_id}


@app.delete("/projectspage/ongingprojects/{project_id}")
async def delete_ongoing_project(project_id: str):
    data = load_data()

    if project_id not in data["onoging_projects"]:
        return {"status": "error", "message": "Project not found"}

    del data["ongoing_projects"][project_id]
    save_data(data)

    return {"status": "deleted", "project_id": project_id}



@app.get("/projectspage/upcomingprojects")
async def get_upcoming_projects():
    data = load_data()
    return data["upcoming_projects"]

@app.post("/projectspage/upcomingprojects/add")
async def add_upcoming_peoject(project: Upcoming_Project):
    data = load_data()

    # Create unique ID
    new_id = f"proj_{len(data['upcoming_projects']) + 1}"

    data["upcoming_projects"][new_id] = {
        "title": project.title,
        "description": project.description
    }

    save_data(data)

    return {"status": "success", "project_id": new_id}

@app.delete("/projectspage/upcomingprojects/{project_id}")
async def delete_upcoming_project(project_id: str):
    data = load_data()

    if project_id not in data["upcoming_projects"]:
        return {"status": "error", "message": "Project not found"}

    del data["upcoming_projects"][project_id]
    save_data(data)

    return {"status": "deleted", "project_id": project_id}

# Contact Page Route:
@app.get("/contactpage")
async def get_contact_page():
    return website_data["contactpage"]

# Contact Page Sub-Section Route:
@app.get("/contactpage/contactdetails")
async def get_contact_details():
    return website_data["contactpage"]["contact_details"]

@app.get("/contactpage/contactformguide")
async def get_contact_form_guide():
    return website_data["contactpage"]["contact_form_guide"]

# Account Page Route:
@app.get("/accountpage")
async def get_account_page():
    return website_data["accountpage"]

# Account Page Sub-Section Routes:
@app.get("/accountpage/login")
async def get_login_info():
    return website_data["accountpage"]["login"]

@app.get("/accountpage/signup")
async def get_signup_info():
    return website_data["accountpage"]["sign_up"]


class Query(BaseModel):
    message: str

@app.post("/assistant")
async def chat(query: Query):
    response = await assistant(query.message)
    return {"assistant_response": response}

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],   # allow all origins (you can restrict later)
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# =========================
# RUN APP (for testing)
# =========================
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)