package api

import (
	"encoding/json"
	"io/fs"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"

	"github.com/go-chi/chi/v5"
	chimiddleware "github.com/go-chi/chi/v5/middleware"
	"github.com/go-chi/cors"
	"github.com/gorilla/sessions"
	"xorm.io/xorm"

	"github.com/prometheus/client_golang/prometheus/promhttp"

	"github.com/forgeo/forgebucket/internal/api/handlers"
	"github.com/forgeo/forgebucket/internal/api/middleware"
	"github.com/forgeo/forgebucket/internal/config"
	"github.com/forgeo/forgebucket/internal/domain/sbom"
	"github.com/forgeo/forgebucket/internal/domain/oci"
	"github.com/forgeo/forgebucket/internal/domain/scanning"
	"github.com/forgeo/forgebucket/internal/domain/signing"
	"github.com/forgeo/forgebucket/internal/domain/vulnscan"
	"github.com/forgeo/forgebucket/internal/events"
	"github.com/forgeo/forgebucket/internal/observability"
)

func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, bus events.EventBus, artifactRoot string, staticFiles fs.FS, keys signing.KeyStore, sbomGen *sbom.Generator, ociRegistry *oci.Registry, scanner *scanning.Scanner, vulnScanner *vulnscan.Scanner) http.Handler {
	r := chi.NewRouter()

	r.Use(chimiddleware.Logger)
	r.Use(chimiddleware.RealIP)
	r.Use(chimiddleware.Recoverer)
	r.Use(observability.Middleware())
	r.Use(cors.Handler(cors.Options{
		AllowedOrigins:   []string{"http://localhost:5173", cfg.InstanceURL},
		AllowedMethods:   []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
		AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
		AllowCredentials: true,
		MaxAge:           300,
	}))

	csrf  := middleware.CSRF(!cfg.Debug)
	auth  := middleware.NewAuth(store, engine, handlers.LookupAccessToken)
	audit := middleware.AuditLog(engine, bus)

	repoH    := handlers.NewRepoHandler(engine, cfg)
	userH    := handlers.NewUserHandler(engine, store)
	prH      := handlers.NewPRHandler(engine)
	pipeH    := handlers.NewPipelineHandler(engine)
	wsH      := handlers.NewWSHandler(bus)
	gitH     := handlers.NewGitHTTPHandler(engine, cfg, bus)
	issueH   := handlers.NewIssueHandler(engine)
	sshKeyH  := handlers.NewSSHKeyHandler(engine)
	memberH  := handlers.NewMemberHandler(engine)
	keyH      := handlers.NewDeployKeyHandler(engine)
	tokenH    := handlers.NewAccessTokenHandler(engine)
	workflowH  := handlers.NewWorkflowHandler(engine)
	webhookH   := handlers.NewWebhookHandler(engine)
	prSettingsH := handlers.NewPRSettingsHandler(engine)
	lfsH        := handlers.NewLFSHandler(engine)
	exploreH      := handlers.NewExploreHandler(engine)
	dashH         := handlers.NewDashboardHandler(engine)
	auditH        := handlers.NewAuditHandler(engine)
	healthH       := handlers.NewHealthHandler(engine, bus)
	repoHealthH   := handlers.NewRepoHealthHandler(engine)
	artifactH   := handlers.NewArtifactHandler(engine, artifactRoot, &keys)
	runnerH     := handlers.NewRunnerHandler(engine)
	gitopsH     := handlers.NewGitOpsHandler(engine, bus)
	fedH         := handlers.NewFederationHandler(engine, cfg)
	envH        := handlers.NewEnvironmentHandler(engine, bus)
	timelineH   := handlers.NewTimelineHandler(engine, cfg.RepoRoot)
	workspaceH  := handlers.NewWorkspaceHandler(engine, cfg)
	secretH     := handlers.NewSecretHandler(engine, cfg.SessionSecret)
	sbomH       := handlers.NewSBOMHandler(engine, sbomGen)
	ociH        := handlers.NewOCIRegistryHandler(engine, ociRegistry)
	scanH       := handlers.NewScanningHandler(engine, scanner)
	vulnH       := handlers.NewVulnScanHandler(engine, vulnScanner)

	// ── Git smart-HTTP transport ───────────────────────────────────────────────
	// Regex constraint ensures only *.git paths match, so asset/SPA URLs
	// with two path segments (e.g. /assets/main.js) fall through to the
	// SPA catch-all instead of being swallowed here.
	r.Route("/{owner}/{repoGit:.*\\.git}", func(r chi.Router) {
		r.Get("/info/refs", gitH.ServeGit)
		r.Post("/git-upload-pack", gitH.ServeGit)
		r.Post("/git-receive-pack", gitH.ServeGit)
	})

	// ── Ops endpoints (root-level, no auth, standard paths for k8s/Prometheus) ──
	r.Get("/health", healthH.Health)
	r.Get("/metrics", promhttp.Handler().ServeHTTP)

	r.Route("/api/v1", func(r chi.Router) {

		// ── Public ────────────────────────────────────────────────────────────
		r.Get("/explore/repos", exploreH.Repos)
		r.Get("/explore/users", exploreH.Users)

		// Generates a CSRF token + cookie. SPA calls this once on load.
		r.Get("/csrf", func(w http.ResponseWriter, r *http.Request) {
			token, err := middleware.NewCSRFToken(w, !cfg.Debug)
			if err != nil {
				http.Error(w, `{"error":"could not generate CSRF token"}`, http.StatusInternalServerError)
				return
			}
			w.Header().Set("Content-Type", "application/json")
			json.NewEncoder(w).Encode(map[string]string{"token": token})
		})

		// ── Auth (CSRF validated, no session required) ─────────────────────────
		r.With(csrf).Post("/auth/register", userH.Register)
		r.With(csrf).Post("/auth/login", userH.Login)
		r.With(csrf).Post("/auth/logout", userH.Logout)

		// ── Protected (session + CSRF for mutations) ──────────────────────────
		r.Group(func(r chi.Router) {
			r.Use(auth.Require)
			r.Use(audit)

			r.Get("/me", userH.Me)
			r.Get("/dashboard", dashH.Get)
			r.Get("/audit", auditH.List)
			r.Get("/secrets/leaks", scanH.ListAllSecrets)
			r.Get("/vulnerabilities", vulnH.ListAll)
			r.Get("/pipelines/runs", pipeH.ListRecentRuns)

			// Workspace routes
			r.Get("/workspaces", workspaceH.ListWorkspaces)
			r.With(csrf).Post("/workspaces", workspaceH.CreateWorkspace)
			r.Route("/workspaces/{handle}", func(r chi.Router) {
				r.Get("/", workspaceH.GetWorkspace)
				r.With(csrf).Patch("/", workspaceH.UpdateWorkspace)
				r.With(csrf).Delete("/", workspaceH.DeleteWorkspace)
				r.Get("/repos", workspaceH.ListRepos)
				r.Route("/members", func(r chi.Router) {
					r.Get("/", workspaceH.ListMembers)
					r.With(csrf).Post("/", workspaceH.AddMember)
					r.With(csrf).Patch("/{username}", workspaceH.UpdateMember)
					r.With(csrf).Delete("/{username}", workspaceH.RemoveMember)
				})
				r.Get("/secrets", secretH.ListWorkspaceSecrets)
				r.With(csrf).Post("/secrets", secretH.UpsertWorkspaceSecret)
				r.With(csrf).Delete("/secrets/{name}", secretH.DeleteWorkspaceSecret)
			})

			// Global secrets (admin)
			r.Get("/admin/secrets", secretH.ListGlobalSecrets)
			r.With(csrf).Post("/admin/secrets", secretH.UpsertGlobalSecret)
			r.With(csrf).Delete("/admin/secrets/{name}", secretH.DeleteGlobalSecret)

			r.Route("/admin", func(r chi.Router) {
				r.Get("/runners", runnerH.List)
				r.With(csrf).Post("/runners/register", runnerH.Register)
			})

			// SSH key management
			r.Get("/user/keys", sshKeyH.List)
			r.With(csrf).Post("/user/keys", sshKeyH.Add)
			r.With(csrf).Delete("/user/keys/{keyID}", sshKeyH.Delete)

			r.Route("/repos", func(r chi.Router) {
				r.Get("/", repoH.List)
				r.With(csrf).Post("/", repoH.Create)
				r.With(csrf).Post("/import", repoH.Import)
				r.Route("/{owner}/{repo}", func(r chi.Router) {
					r.Get("/", repoH.Get)
					r.With(csrf).Patch("/", repoH.Update)
					r.With(csrf).Delete("/", repoH.Delete)
					r.Get("/tree", repoH.Tree)
					r.Get("/avatar", repoH.GetAvatar)
					r.With(csrf).Post("/avatar", repoH.UploadAvatar)
					r.Get("/blob", repoH.Blob)
					r.With(csrf).Put("/blob", repoH.UpdateBlob)
					r.Get("/commits", repoH.Commits)
					r.Get("/branches", repoH.Branches)
					r.Get("/diff", repoH.Diff)
					r.Route("/pulls", func(r chi.Router) {
						r.Get("/", prH.List)
						r.With(csrf).Post("/", prH.Create)
						r.Get("/{prID}", prH.Get)
						r.With(csrf).Patch("/{prID}", prH.Update)
						r.With(csrf).Post("/{prID}/merge", prH.Merge)
						r.With(csrf).Post("/{prID}/close", prH.Close)
						r.With(csrf).Post("/{prID}/reopen", prH.Reopen)
					})
					r.Route("/issues", func(r chi.Router) {
						r.Get("/", issueH.List)
						r.With(csrf).Post("/", issueH.Create)
						r.Get("/{issueNum}", issueH.Get)
						r.With(csrf).Post("/{issueNum}/close", issueH.Close)
						r.With(csrf).Post("/{issueNum}/reopen", issueH.Reopen)
					})
					r.Get("/pipelines", pipeH.ListPipelines)
					r.Route("/runs", func(r chi.Router) {
						r.Get("/", pipeH.ListRuns)
						r.Route("/{runID}", func(r chi.Router) {
							r.Get("/", pipeH.GetRun)
							r.With(csrf).Post("/cancel", pipeH.CancelRun)
							r.Route("/jobs/{jobID}", func(r chi.Router) {
								r.Get("/logs", pipeH.GetJobLogs)
								r.With(csrf).Post("/retry", pipeH.RetryJob)
							})
							r.Get("/artifacts", artifactH.List)
							r.With(csrf).Post("/artifacts", artifactH.Upload)
							r.Get("/sbom", sbomH.GetForRun)
							r.Get("/sbom/document", sbomH.GetDocumentForRun)
						})
					})
					r.Get("/artifacts/{artifactID}/download", artifactH.Download)
					r.Get("/artifacts/{artifactID}/signature", artifactH.GetSignature)
					r.Get("/artifacts/{artifactID}/verify", artifactH.VerifySignature)
					r.Route("/members", func(r chi.Router) {
						r.Get("/", memberH.List)
						r.With(csrf).Post("/", memberH.Add)
						r.With(csrf).Patch("/{username}", memberH.UpdatePermission)
						r.With(csrf).Delete("/{username}", memberH.Remove)
					})
					r.Route("/keys", func(r chi.Router) {
						r.Get("/", keyH.List)
						r.With(csrf).Post("/", keyH.Create)
						r.With(csrf).Delete("/{keyID}", keyH.Delete)
					})
					r.Route("/tokens", func(r chi.Router) {
						r.Get("/", tokenH.List)
						r.With(csrf).Post("/", tokenH.Create)
						r.With(csrf).Delete("/{tokenID}", tokenH.Delete)
					})
					r.Route("/branch-protections", func(r chi.Router) {
						r.Get("/", workflowH.ListBranchProtections)
						r.With(csrf).Post("/", workflowH.CreateBranchProtection)
						r.With(csrf).Patch("/{bpID}", workflowH.UpdateBranchProtection)
						r.With(csrf).Delete("/{bpID}", workflowH.DeleteBranchProtection)
					})
					r.Get("/branching-model", workflowH.GetBranchingModel)
					r.With(csrf).Put("/branching-model", workflowH.UpdateBranchingModel)
					r.Get("/merge-strategies", workflowH.GetMergeStrategies)
					r.With(csrf).Put("/merge-strategies", workflowH.UpdateMergeStrategies)
					r.Route("/webhooks", func(r chi.Router) {
						r.Get("/", webhookH.List)
						r.With(csrf).Post("/", webhookH.Create)
						r.With(csrf).Patch("/{whID}", webhookH.Update)
						r.With(csrf).Delete("/{whID}", webhookH.Delete)
						r.With(csrf).Post("/{whID}/test", webhookH.Test)
					})
					r.Route("/default-reviewers", func(r chi.Router) {
						r.Get("/", prSettingsH.ListDefaultReviewers)
						r.With(csrf).Post("/", prSettingsH.AddDefaultReviewer)
						r.With(csrf).Delete("/{username}", prSettingsH.RemoveDefaultReviewer)
					})
					r.Get("/default-description", prSettingsH.GetDefaultDescription)
					r.With(csrf).Put("/default-description", prSettingsH.UpdateDefaultDescription)
				r.Get("/excluded-files", prSettingsH.GetExcludedFiles)
				r.With(csrf).Put("/excluded-files", prSettingsH.UpdateExcludedFiles)
				r.Get("/timeline", timelineH.GetTimeline)
				r.Get("/secrets", secretH.ListRepoSecrets)
				r.With(csrf).Post("/secrets", secretH.UpsertRepoSecret)
				r.With(csrf).Delete("/secrets/{name}", secretH.DeleteRepoSecret)
				r.Get("/secrets/leaks", scanH.ListSecrets)
				r.With(csrf).Post("/secrets/leaks/{leakID}/dismiss", scanH.DismissSecrets)
				r.Get("/vulnerabilities", vulnH.List)
				r.With(csrf).Post("/vulnerabilities/scan", vulnH.Scan)
				r.With(csrf).Post("/vulnerabilities/{findingID}/dismiss", vulnH.Dismiss)
				r.Get("/lfs-settings", lfsH.Get)
				r.With(csrf).Put("/lfs-settings", lfsH.Update)
				r.Get("/health", repoHealthH.Get)
				r.Get("/sbom", sbomH.GetLatest)
				r.Get("/sbom/document", sbomH.GetLatestDocument)
				r.With(csrf).Post("/sbom/generate", sbomH.Generate)
				r.Route("/environments", func(r chi.Router) {
					r.Get("/", envH.ListEnvironments)
					r.With(csrf).Post("/", envH.CreateEnvironment)
					r.Route("/{envName}", func(r chi.Router) {
						r.Get("/", envH.GetEnvironment)
						r.With(csrf).Patch("/", envH.UpdateEnvironment)
						r.With(csrf).Delete("/", envH.DeleteEnvironment)
						r.Route("/deployments", func(r chi.Router) {
							r.Get("/", envH.ListDeployments)
							r.With(csrf).Post("/", envH.CreateDeployment)
							r.With(csrf).Patch("/{deployID}/status", envH.UpdateDeploymentStatus)
						})
						r.Get("/secrets", secretH.ListEnvSecrets)
						r.With(csrf).Post("/secrets", secretH.UpsertEnvSecret)
						r.With(csrf).Delete("/secrets/{name}", secretH.DeleteEnvSecret)
						r.Route("/gitops", func(r chi.Router) {
							r.Get("/", gitopsH.GetConfig)
							r.With(csrf).Put("/", gitopsH.UpsertConfig)
							r.With(csrf).Delete("/", gitopsH.DeleteConfig)
							r.With(csrf).Post("/sync", gitopsH.TriggerSync)
							r.Get("/drift", gitopsH.GetDriftStatus)
							r.Get("/drift/history", gitopsH.ListDriftEvents)
							r.With(csrf).Post("/drift/{driftID}/acknowledge", gitopsH.AcknowledgeDrift)
						})
					})
				})
			})
		})
	})
	})

	r.With(auth.Optional).Get("/ws", wsH.Hub)

	// ── OCI Registry (Distribution Spec v1.1) ─────────────────────────────────
	r.HandleFunc("/v2", ociH.ServeOCI)
	r.HandleFunc("/v2/*", ociH.ServeOCI)

	// ── ForgeFed Repository Actors (cross-instance PRs) ───────────────────────
	// These must sit outside the auth-protected group since remote instances
	// deliver activities without session cookies.
	r.Get("/repos/{owner}/{repo}/actor", fedH.RepoActor)
	r.Post("/repos/{owner}/{repo}/inbox", fedH.RepoInbox)

	// ── ActivityPub / federation (root-level, no auth) ────────────────────────
	// Must be registered before the /* catch-all so they are not proxied to Vite.
	r.Get("/.well-known/webfinger", fedH.WebFinger)
	r.Get("/users/{username}", fedH.Actor)
	r.Post("/users/{username}/inbox", fedH.Inbox)
	r.Get("/users/{username}/outbox", fedH.OutboxGet)
	r.Get("/users/{username}/followers", fedH.Followers)
	r.Get("/users/{username}/following", fedH.Following)

	// In debug mode proxy non-API routes to the Vite dev server so :8080 works too.
	// In production the built React app is embedded and served from staticFiles.
	if cfg.Debug {
		r.Handle("/*", viteProxy("http://localhost:5173"))
	} else {
		r.Handle("/*", spaHandler(staticFiles))
	}

	return r
}

func viteProxy(target string) http.Handler {
	proxy := &httputil.ReverseProxy{
		Rewrite: func(r *httputil.ProxyRequest) {
			r.SetURL(mustParseURL(target))
			r.Out.Host = r.In.Host
		},
	}
	return proxy
}

func mustParseURL(raw string) *url.URL {
	u, err := url.Parse(raw)
	if err != nil {
		panic(err)
	}
	return u
}

func spaHandler(staticFiles fs.FS) http.Handler {
	fileServer := http.FileServer(http.FS(staticFiles))
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// fs.FS paths must not have a leading slash.
		path := strings.TrimPrefix(r.URL.Path, "/")
		if path == "" {
			path = "."
		}
		_, err := staticFiles.Open(path)
		if err != nil {
			r.URL.Path = "/"
		}
		fileServer.ServeHTTP(w, r)
	})
}
